Question
I am creating my first plugin and in it users will be able (among other things) to create new post via custom form from wordpress backend. This post uses custom post type and custom taxonomy. Form creates new post but it fails to set custom taxomony.
Creating post regularly (not via my custom form) works fine ie. allows me to add custom taxomony to it.
Custom post type and custom taxonomies are registered by the book, terms are already inserted in db.
*taxonomy is not a variable for debugging purposes
add_action('plugins_loaded', 'newpost');
function newpost() {
if (isset($_POST['new_post']) == '1') {
$post_title = $_POST['posttitle'];
$post_content = $_POST['postcontent'];
$new_post = array(
'ID' => '',
'post_author' => 1,
'post_type' => 'cars',
'post_content' => $post_content,
'post_title' => $post_title,
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_status' => 'publish',
'tax_input' => array('cars' => array('bmw', 'audi'))
);
$post_id = wp_insert_post($new_post);
}
}
I’ve even tried to remove ‘tax_input’ and use wp_set_post_terms and wp_set_object_terms but results were same. Two days I’m stuck on this, so any help would be greatly appreciated…
Solution
The solution was to change plugins_loaded to init with low priority.
add_action( 'init', 'newpost', 200 );
So the issue was that user privileges have not yet been set, upon firing the plugin.
Have you tried
wp_set_object_terms?
…which needs to be placed after your call towp_insert_post
as it requires the post ID in order to attach the correct terms, to the right taxonomy with the right post.