WordPress.org

Ready to get started?Download WordPress

Forums

wp_insert_post with category variable not working (2 posts)

  1. mittul.agile
    Member
    Posted 1 year ago #

    hi .. i m encountering a strange problem in which i m inserting a post using the category variable .. here below is my working code ..

    ------------------------------------
    $new_post = array(
    'post_title' => $title,
    'post_content' => $description,
    'post_date' => $post_date,
    'post_status' => 'future',
    'post_category' => array(18,19,20),
    );

    //SAVE THE POST
    $pid = wp_insert_post($new_post);
    ------------------------------------

    this code works fine .. however when i try to add categories into an array with variable .. then it is only adding first category value into the post ..

    ------------------------------------
    $new_array = array(18,19,20);
    $final_cat_id = implode(',',$new_cat_ID);
    echo $final_cat_id;

    $title = 'title';
    $description = 'description';
    $post_date = date("Y-m-d H:i:s");

    // Create post object

    $new_post = array(
    'post_title' => $title,
    'post_content' => $description,
    'post_date' => $post_date,
    'post_status' => 'future',
    'post_category' => array($final_cat_id),
    );

    //SAVE THE POST
    $pid = wp_insert_post($new_post);
    ------------------------------------

    i m getting 18,19,20 when i m echoing the $final_cat_id but it is only adding 18 category when inserting a post ..

    can someone help me where i am going wrong . .

  2. mittul.agile
    Member
    Posted 1 year ago #

    ok . i have sorted out my problem by not imploding it ..

    just do this

    'post_category' => $new_array,

    remove the lines

    $final_cat_id = implode(',',$new_cat_ID);
    echo $final_cat_id;

    as it will automatically imploding while inserting a post .. cheers !

Topic Closed

This topic has been closed to new replies.

About this Topic