woocommerce offtopic - How to add existing categories into a post using wp_insert_post

admin2025-01-07  7

I tried to add a category based on a post as seen on this link:
How we add new categories by wp_insert_post

Here, I added 'post_category' and default category IDs in an array as shown below:

$my_post = array(
    'post_title'    => 'test',
    'post_content'  => 'hello',
    'post_status'   => 'publish',
    'post_author'   =>  1,
    'post_type'     => 'product',
    'post_category' => array(2,3,4,5)
 );
 $post_id = wp_insert_post($my_post);

All of the fields above have been added, except for the post_category. I wanted to add more than one category per product, and what I am using is an array.

What is probably the problem here?

I tried to add a category based on a post as seen on this link:
How we add new categories by wp_insert_post

Here, I added 'post_category' and default category IDs in an array as shown below:

$my_post = array(
    'post_title'    => 'test',
    'post_content'  => 'hello',
    'post_status'   => 'publish',
    'post_author'   =>  1,
    'post_type'     => 'product',
    'post_category' => array(2,3,4,5)
 );
 $post_id = wp_insert_post($my_post);

All of the fields above have been added, except for the post_category. I wanted to add more than one category per product, and what I am using is an array.

What is probably the problem here?

Share Improve this question asked Apr 19, 2017 at 6:45 smzappsmzapp 1212 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

You can use wp_set_object_terms() to assign taxonomy terms to a post.

wp_set_object_terms($post_id, $terms, $taxonomy, true);

Where $terms - A single term slug, single term id, or array of either term slugs or ids. Will replace all existing related terms in this taxonomy.

See documentation: https://codex.wordpress.org/Function_Reference/wp_set_object_terms

Edit:

In your case, it will look like:

wp_set_object_terms($post_id, array(2,3,4,5), 'category', true);

Please check for any syntax error.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736252722a68.html

最新回复(0)