Programmatically add terms to custom post types

I find out the problem and the solution. I debugged the “wp_set_object_terms” by using “is_wp_error” and I got “Invalid Taxonomy” message, then I realized that when the posts was being created that term didn’t exists. So I change the hook to “init” in the programmatically_create_post() function, and voila!

Below this line the code working:

    <?php
// TO DO WHEN THEME IS ACTIVATED ///////////////////////
if (isset($_GET['activated']) && is_admin()){

  // 3. Add term "mosaic-home" to custom taxonomy "tiles_categories"
    function example_insert_category() {
      wp_insert_term(
        'Mosaic - Home',
        'tiles_categories',
        array(
          'description' => 'Add Tiles here to load in first term',
          'slug'    => 'mosaic-home'
          )
        );
      }
    add_action('init','example_insert_category');

  // 4. Make loop for creating 24 posts
    function create_frontles_posts() {
      $x = 1;

      do {
        $post_id = wp_insert_post(array(
            'comment_status'  =>  'closed',
            'ping_status'   =>  'closed',
            'post_author'   =>  1,
            'post_name'   =>  'tile'.$x,
            'post_title'    =>  'Tile',
            'post_status'   =>  'publish',
            'post_type'   =>  'frontiles',
            // 'tax_input' =>   array('tiles_categories' => 2),
          ));
          wp_set_object_terms($post_id, 'mosaic-home', 'tiles_categories', true);

            $x++;
          } while ($x <= 24);
        }


// 5. add the loop to the function for create posts
  function programmatically_create_post() {

    // Initialize the page ID to -1. This indicates no action has been taken.
    $post_id = -1;
    $title="";
    // If the page doesn't already exist, then create it
    if( null == get_page_by_title( $title ) ) {
        create_frontles_posts();
        } else {
              // Otherwise, we'll stop
              $post_id = -2;
      } 
    } 
    add_filter( 'init', 'programmatically_create_post' );

} // end to do on activation
?>

Leave a Comment