John Davidson

php - wp_set_object_terms not working with custom taxonomy and custom post types

0 comments
Message:


$post_type = 'machine';
$title = $_POST['name'];
$new_post = array(
'post_title' => $title,
'post_status' => 'publish',
'post_type' => $post_type,
);
$pid = wp_insert_post($new_post);
$category_id = trim($_POST['category']);
$taxonomy = 'machine_categories';
wp_set_object_terms( $pid, (int)$category_id, $taxonomy, true );

Here i create a new post type machine and new taxonomy machine_categories
A new custom form created in the front end


<div class="form-group">
<input type="text" class="form-input" name="name" id="name" placeholder="Post Title" />
</div>
<div class="form-group">
<label>Post Category</label>
<select class="form-input" name="category" id="category">
<option>--Select--</option>
<?php
$terms=g et_terms( array( 'taxonomy'=>'machine_categories', 'hide_empty' => false, ) );
if ( ! empty( $terms ) && is_array( $terms ) )
{
foreach ( $terms as $term ) {
?>
<option value="<?php echo $term->term_id; ?>"><?php echo $term->name; ?></option>
<?php
}
}
?>
</select>
</div>

Here is the dropdown code in the frontend, when i submit the post there is an error shows Invalid Taxonomy
This taxonomy and post type created using Custom post type ui plugin.



My Answer:
$title,
'post_type' => $post_type,
'post_status' => 'publish'
);

$post_id = wp_insert_post($new_post);

$taxonomy = 'machine_category';
$terms = array('category1', 'category2');

wp_set_object_terms($post_id, $terms, $taxonomy);

Rate this post

5 of 5 based on 1504 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us