• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

My Monkey Do

A Log of Coding Solutions

  • Home
  • Web Hosts
  • Tools
  • About

wp_insert_post post_category problem

September 11, 2012 by Webhead

Problem

I was wp_insert_post to programmatically create a custom post type with a custom category.  Using the following code did not work however.

$new_post = array(
‘post_title’ => ‘some title’,
‘post_content’ => ‘some description’,
‘post_status’ => ‘publish’,
‘post_author’ => $admin_user->ID,
‘post_category’ => array($category->term_id)
);
wp_insert_post($new_post);

Solution

If I read the wordpress codex better and more thoroughly I probably would have seen that there is another special parameter for custom taxonomies.  Instead of using ‘post_category’ I should be using ‘tax_input’ for custom taxonomy categories.  So instead of the ‘post_category’ line, it would look like:

‘tax_input’ => array($category->taxonomy => array($category->cat_name ));

If this doesn’t work, like it didn’t for me because I’m using it in a CRON, the user you are using may not have rights to modify the taxonomy.  in that case, as the docs say, use wp_set_object_terms.  The problem is that wp_insert_post uses current_user_can to detect if the current user can add the taxonomy.  The issue is documented here: http://core.trac.wordpress.org/ticket/19373

 

source: http://wordpress.org/support/topic/problem-with-wp_insert_post-for-custom-post-type-category-is-not-associated
keywords:  wordpress post_category wp_insert_post

Filed Under: Coding Tagged With: php, wordpress

Primary Sidebar

Topics

apache apple block editor chrome cms css debug eCommerce embed firebug firefox git gmail goDaddy google hosting htaccess html html 5 IE crap image iPad iPhone javascript jquery linux localization mac os x ms sql mysql open source optimize php php 5.3 responsive rest api seo svg tinymce woocommerce wordpress wpengine xss yii youtube




Categories

  • Coding
  • Off the Shelf
  • Plugins
  • Random Thoughts
  • Server Stuff
  • Tools