简体   繁体   中英

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')

Any ideas?

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 );

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM