0

how to insert content into my taxonomy this code is correct or not?

   // Create post object
  $my_post = array(
 'post_title' => 'My post',
 'post_content' => 'This is my post.',
 'post_status' => 'publish',
 'post_author' => 1,
  'tax_input' => array( 'taxonomy_name' => array( 'Newpostlist' ) ) , 
 'post_category' => array(8,39),

   );

      // Insert the post into the database
       wp_insert_post( $my_post );
2
  • Taxonomies don’t have content, they are meta data.
    – fuxia
    Commented Apr 4, 2012 at 19:17
  • He means "insert terms associated with a taxonomy" Commented Apr 4, 2012 at 19:20

2 Answers 2

1

You're using tax_input incorrectly. You're not literally supposed to say taxonomy_name, you're supposed to enter the name of your custom taxonomy. See https://codex.wordpress.org/Function_Reference/wp_insert_post. So, assuming your taxonomy is called 'ninja_turtles' and you are tagging your post with 'donatello' and 'michelangelo':

// Create post object
$my_post = array(
    'post_title' => 'My post',
    'post_content' => 'This is my post.',
    'post_status' => 'publish',
    'post_author' => 1,
    'tax_input' => array( 'ninja_turtles' => array( 'donatello', 'michelangelo' ) ) , 
    'post_category' => array(8,39),
);

// Insert the post into the database
wp_insert_post( $my_post );

For no particular reason (other than that it makes me feel like I have more granular control), I personally prefer not to use tax_input but to use the standalone function wp_set_post_terms() https://codex.wordpress.org/Function_Reference/wp_set_post_terms after the post is created:

// Create post object
$my_post = array(
    'post_title' => 'My post',
    'post_content' => 'This is my post.',
    'post_status' => 'publish',
    'post_author' => 1,
    'post_category' => array(8,39),
);

// Insert the post into the database
$post_id = wp_insert_post( $my_post );

// If all was successful, add the terms
if ( $post_id ) {
    wp_set_post_terms( $post_id, array( 'donatello', 'michelangelo' ), 'ninja_turtles' );
}
0

This code appears to be correct, but the only way to find out is to try it. You can find more information about adding posts at the wp_insert_post() page on the WordPress codex.

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.