Add custom field to attachments in a specific category

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;
}

Leave a Comment