WordPress, add post to custom taxonomy’s category

I am trying to add a post to a category under taxonomy cate. The code I am using is:

$user = get_user_by( 'email', $_POST['user'] );
$id = array(
    'post_title'    => $_POST['title'],
    'post_content'  => $_POST['content'],
    'post_date'     => date('Y-m-d H:i:s'),
    'post_author'   => $user->ID,
    'taxonomy' => ('cate'),
    'post_type'     => 'ad',
    'post_category' => array(425),
    'post_status'   => 'publish',
); 
 $user_id = wp_insert_post($id);
if ( ! is_wp_error( $user_id ) ) {
   $odgovor["success"] = 1;

}

The post is added but it’s added under category ‘uncategorized” and not under desired category ID. This system works properly when custom post type is not used. (In this case taxonomy ‘cate’)

Read More

Any ideas?

Related posts

2 comments

  1. You need wp_set_object_terms, which takes post ID, terms, taxonomy, and append as parameters. For example:

    $user_id = wp_insert_post( $id );
    
    wp_set_object_terms( $user_id, 'cate', 'category', true );
    
  2. I solved it like this:

    $id = array(
            'post_title'    => $_POST['title'],
            'post_content'  => $_POST['content'],
            'post_date'     => date('Y-m-d H:i:s'),
            'post_author'   => $user->ID,
            'post_type'     => 'ad',
            'post_status'   => 'publish',
        ); 
         $user_id = wp_insert_post($id);
         wp_set_object_terms($user_id, 416, 'cate', true);
        if ( ! is_wp_error( $user_id ) ) {
           $odgovor["success"] = 1;
    
        }
    

    Josh showed me the way, but his syntax wasn’t right. It’ category first, taxonomy second, and some things had to be removed.

Comments are closed.