为附件添加自定义字段

    为附件添加自定义字段

    一般来说,WordPress媒体上传模块有足够的数据字段识别所有元素,图像、视频等等,然而有时,你不仅需要识别,例如一个图像,虽然有确切的url,但我们需要了解一些信息来源,技术资料,拍摄地点,出现在一张照片的人,等等。在这种情况下,您需要添加一些WordPress媒体上传的数据字段。

    在这个例子中,我们假设我们想要添加的名字照片拍摄的地方,照片上的人这两个额外的字段。WordPress已经存储(速度、光圈、焦距、日期和时间,等等这些数据),<

    WP函数wp_get_attachment_metadata() (见的官方文档wp_get_attachment_metadata

    在第一步中,我们显示这两个新字段在WP媒体上传界面,要做到这一点,我们将使用一个过滤器attachment_fields_to_edit让我们添加新字段后常见的媒体数据字段。 这个过滤器接收两个参数:

    • the array of the fields on the screen.
    • the WP $post
    // wp官方文档
    $fields['field_name'] = array(
        'label' => 'This is the label',      // the label for field on the screen
        'input' => 'type of the field',      // text, number, html....
        'value' => $value,                   // The value for this field
        'helps' => 'Help text'               //  This is a text displayed next to field
    )

    所以函数插入两个新字段应该是这样的。

    function adding_custom_media_fields ( $form_fields, $post ) {
     
     $form_fields['place_name'] = array(
     'label' => '地名',
     'input' => 'text',
     'value' => get_post_meta( $post->ID, 'place_name', true ),
     'helps' => '拍摄照片的地点名称',
     );
     $form_fields['client_name'] = array(
     'label' => '客户名称',
     'input' => 'text',
     'value' => get_post_meta( $post->ID, 'client_name', true ),
     'helps' => '被拍摄者的名字',
     );
     return $form_fields;
    
    }
    add_filter( 'attachment_fields_to_edit', 'adding_custom_media_fields', 10, 2 );

     

    将这个函数添加到过滤器attachment_fields_to_edit我们会在媒体上传时看到两个新字段。

    为附件添加自定义字段
    最后我们执行保存函数

    add_filter( 'attachment_fields_to_edit', 'adding_custom_media_fields', 10, 2 );
    
    function saving_custom_media_fields ( $post, $attachment ) {
    
    if( isset( $attachment['place_name'] ) )
    update_post_meta( $post['ID'], 'place_name', $attachment['place_name'] );
    if( isset( $attachment['client_name'] ) )
    update_post_meta( $post['ID'], 'place_name', $attachment['client_name'] );
    return $post;
    
    }
    add_filter( 'attachment_fields_to_save', 'saving_custom_media_fields', 10, 2 );

     

    Responses

    您的电子邮箱地址不会被公开。 必填项已用*标注

    Up Next:

    wordpress后台登录页面样式

    wordpress后台登录页面样式