编辑媒体时添加Metabox-但仅适用于图像

时间:2020-01-27 作者:gordie

是否可以为媒体(附件)添加元盒,但前提是它们是图像?我不想在其他文件类型上使用此metabox。

谢谢

1 个回复
SO网友:Dip Patel

戈迪

下面是一个用于以下可能mime类型的元框示例:“image/jpeg”、“image/gif”、“image/png”、“image/bmp”、“image/tiff”、“image/x-icon”

//add meta_box for image mime types only
function add_our_attachment_meta(){
    $attachment_id          = $_REQUEST[\'post\'];
    $attachment_mime_type   = get_post_mime_type($attachment_id);
    $possible_mime_types    = array(\'image/jpeg\',\'image/gif\',\'image/png\',\'image/bmp\',\'image/tiff\',\'image/x-icon\');
    if(in_array($attachment_mime_type, $possible_mime_types)){
            add_meta_box( \'custom-attachment-meta-box\', 
                            \'Attachment Extra Details\', 
                            \'our_attachment_meta_box_callback\',
                            \'attachment\',
                            \'normal\',
                            \'low\');
    }
}
add_action( \'admin_init\', \'add_our_attachment_meta\' );

//callback function of custom metabox
function our_attachment_meta_box_callback(){
     global $post; 
     $value = get_post_meta($post->ID, \'featured_photo\', 1);
?>
      <p>This will render inside of the meta box.</p>
    <select name="featured_photo">
     <option value="0" <?php selected( 0, $value ); ?> >No </option>
     <option value="1" <?php selected( 1, $value ); ?> >Yes </option>
    </select>
     <?php
}

//save meta on save post
function save_our_attachment_meta(){
     global $post; 
     if( isset( $_POST[\'featured_photo\'] ) ){
           update_post_meta( $post->ID, \'featured_photo\', $_POST[\'featured_photo\'] );
     }
}
add_action(\'edit_attachment\', \'save_our_attachment_meta\');

如果有任何疑问,请回复,我一定会看一看。

非常感谢。