0

I have a working function that adds a meta field to all attachments (so I can enter the url of a video). I would like this field to populate only on attachments in the "video" category.

I've tried the below, by adding in_category('video') but that didn't work. The field still shows on all attachments.

function attachment_field_url( $form_fields, $post ) {

        $form_fields['video-url'] = array(
        'label' => 'Video URL',
        'input' => 'text',
        'value' => get_post_meta( $post->ID, 'video_url', true ),
        'helps' => 'Add video URL',
    );

    return $form_fields;
}

add_filter( 'attachment_fields_to_edit', 'attachment_field_url', 10, 2 );

function attachment_field_url_save( $post, $attachment ) {

    if( in_category('video')  && !isset ($attachment['video-url'] ) )
update_post_meta( $post['ID'], 'video_url', esc_url( $attachment['video-url'] ) );                             
    return $post;
}

add_filter( 'attachment_fields_to_save', 'attachment_field_url_save', 10, 2 );
1

in_category relies on a global post - it should only be used within the loop. Instead, use the arguments that are passed to your callback to query the categories assigned to the post being edited and check if one of them is video:

$cats = get_the_category( $post['ID'] );
if ( in_array( 'video', wp_list_pluck( $cats, 'slug' ) ) {
    // In "video" category
}

...altogether now:

function attachment_field_url_save( $post, $attachment ) {
    if ( isset( $attachment['video-url'] ) ) {
        $cats = get_the_category( $post['ID'] );

        if ( in_array( 'video', wp_list_pluck( $cats, 'slug' ) ) {
            update_post_meta( $post['ID'], 'video_url', esc_url( $attachment['video-url'] ) );  
        }
    }

    return $post;
}
| improve this answer | |
  • Is that something I would wrap around both functions? Also, I did find an article that says for custom attachment fields of a certain kind (for example, audio files) you wrap the function with: if( substr($post->post_mime_type, 0, 5) == 'audio' ){ // add your custom fields for audio files } Article: code.tutsplus.com/articles/… – BlueHelmet May 28 '16 at 17:38
  • No, you would just use it instead of in_category( 'video' ) in your save function. And yes, you can conditionally add fields depending on mime type as you have described. – TheDeadMedic Jun 3 '16 at 10:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.