1

I want to upload an image and attach to it a category. This is my code:

function upload_cover(WP_REST_Request $request) {

    require_once( ABSPATH . 'wp-admin/includes/image.php' );
    require_once( ABSPATH . 'wp-admin/includes/file.php' );
    require_once( ABSPATH . 'wp-admin/includes/media.php' );

    $attachment_id = media_handle_upload('poster', 0);
    $event = array(
        'post_status' => 'publish',
        'post_type'   => 'poster',
        'meta_input'  => array(),
        'post_category' => array('poster')
    );
    $post_id = wp_insert_post( $event );
    wp_set_post_terms($post_id, 'poster', 'category');
}

The uploader works fine, but no category is attached to the image. I have tried and with these:

$cat_id = get_cat_ID('cover');

add_term_meta( $cat_id, 'poster', $post_id, true );
wp_set_post_categories($post_id, array('poster'), true);
wp_set_post_terms($post_id, array('poster'), 'category');

For the categories for images, I am using this plugin Media Library Categories.

2
  • I don't think it's possible to do this out-of-the box. Media Library files, as far as I know, cannot be assigned a category unless they are an attachment.
    – Pim
    Commented Oct 11, 2018 at 7:41
  • Hi, yes it is attachment, because I can assign to them categories via admin panel after the image is uploaded, but I want to do that via code, because I am using an API.
    – gdfgdfg
    Commented Oct 11, 2018 at 11:02

2 Answers 2

2

First of all, if you want to apply categories to Attachments, you have to enable categories for the attachment.

You can do this by using the register_taxonomy_for_object_type() function. In your plugin file or theme functions file, add the following:

function wp_add_categories_to_attachments() {
    register_taxonomy_for_object_type( 'category', 'attachment' );
}
add_action( 'init' , 'wp_add_categories_to_attachments' );
1
  • Doesn't work. Image is uploaded, but category is not assign to it. I think I don't need this function, because I can add a category to the uploaded image via admin panel, but I want to do that with code.
    – gdfgdfg
    Commented Oct 11, 2018 at 12:58
0

This fix the problem: wp_set_object_terms($attachment_id, 'poster', 'category', true);

https://developer.wordpress.org/reference/functions/wp_set_object_terms/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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