Upload media (image) and set the category – WordPress

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(‘cover’, 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’);

Read more here:: Upload media (image) and set the category – WordPress

Leave a Reply

Your email address will not be published. Required fields are marked *