i am currently working on a snippet to insert a new post dynamically (it’s a custom post type). During this new post creation i need to insert terms in custom taxonomies associated to the custom post type.
I am having the famous “invalid taxonomy” error message and i don’t know how to solve this.
Here is the code i’m using:
- the custom post type is: property
- the custom taxonomy is: type
Code:
// Insert property into DB
$property = array(
'post_title' => $title,
'post_content' => $description,
'post_status' => 'draft',
'post_author' => 1,
'post_type' => 'property'
);
// Insert the post into the database
$property_id = wp_insert_post( $property );
// Taxo Property Type
if( $property_type ) {
// check if term exists
$property_type_term = term_exists( $property_type, 'type' );
if( $property_type_term !== 0 && $term !== null ) {
// Term exists, get the term id
$property_type_term_id = $property_type_term;
} else {
// Create new term
$property_type_term_id = wp_insert_term(
$property_type, // the term
'type' // the taxonomy
);
}
// Assign term id to post
wp_set_post_terms( $property_id, array($property_type_term_id), 'type' );
}
With this code, the post is correctly created but the term not.
Any help would be much appreciated!
first you should set the taxnomy in custom post type you have just set only for post title post content post comments you did not set for custom taxnomy
this query will set the custom taxnomy while creating custom post check this link