wp_insert_post or wp_set_post_terms do not save taxonomy, but wp_set_post_terms does

I have a litlle problem. I have a custom taxonomy ‘rodzaj’ with value i.ex. obrazek. I use this code to add post:

$postArray = array(
                'post_status' => 'publish',
                'post_author'=> get_current_user_id(),
                'post_category'=>array($catId),
                'post_title' => $_POST['titlePhoto'],
                'tax_input' => array( 'rodzaj' => array( 'obrazek') ) , 
);

This code adds a post but without taxonomy. I tried also this:

Read More
wp_set_object_terms($postId, "obrazek", 'rodzaj', false);

Doesn’t work too.

Working code is:

wp_set_post_terms( $postId, array( 'obrazek'), 'rodzaj' );

Why first 2 functions doesn’t work?

I made mistake at the begining. This is full working code:

$catId = get_cat_ID("Obrazki");

         $postArray = array(
            'post_status' => 'publish',
            'post_author'=> get_current_user_id(),
            'post_category'=>array($catId),
            'post_title' => $_POST['titlePhoto'],
            'tags_input' => explode(',', $_POST['tagsPhoto'])
         );


         $postId = wp_insert_post($postArray);
         if($postId) 
         {
              wp_set_object_terms($postId, "obrazek", 'rodzaj', false);

          }

Still doesn’t working:
wp_set_post_terms($postId, “obrazek”, ‘rodzaj’, false);

and
‘tax_input’ => array( ‘rodzaj’ => array( ‘obrazek’) ) in postArray()

Related posts

Leave a Reply

2 comments

  1. Have you tried:

    wp_set_object_terms( $postId, array( 'obrazek'), 'rodzaj' );
    

    wp_set_object_terms and wp_set_post_terms take the same arguments. wp_set_post_terms even uses wp_set_object_terms internally. The main difference being that you used an array in the one that worked, and you didn’t use an array in the one that didn’t work.

  2. If your taxonomy is hierarchical, then the tax_input parameter of wp_insert_post needs an array if ids, not slugs.

    'tax_input' => array(
      'name_of_taxonomy' => array(125) // say your term_id is 125
    )
    

    After doing this, you will probably have to update the term count with something like this:

    add_action('init','reset_terms_counts', 11, 0);
    function reset_terms_counts(){
    
        $terms_ids = get_terms(array(
          'taxonomy' => 'taxonomy_name'
          ,'fields' => 'ids'
          ,'hide_empty' => false
        ));
    
        if(is_array($terms_ids)) wp_update_term_count_now($terms_ids, 'taxonomy_name');
      }
    }