wp_insert_post does not write my post_name

i tried to generate a page via wp_insert_post. That works fine except that the post_name is always written with the same value as the post_title.
Here comes the code snippet:

// Create homesite if not exists

$ins_home = array(
    'post_title' => 'Home',
    'post_name' => 'my-home-site',
    'post_status' => 'publish',
    'post_type' => 'page',
    'comment_status' => 'closed',
    'ping_status' => 'closed'
);

$result = $wpdb->query("SELECT wpost.post_name FROM $wpdb->posts wpost WHERE wpost.post_name = 'my-home-site'");

if($result < 1){// Insert the post into the database
    $page_id = wp_insert_post( $ins_home );
}

Any help is very appreciated.

Read More

Thanks a lot,
Joe

Related posts

Leave a Reply

1 comment

  1. Gr8 job… only thing missing is the action and the timing for it to work…

    try this:

    $ins_home = array(
        'post_title'    =>  'Home',
        'post_name'     =>  'my-home-site',
        'post_status'   => array('publish'),
        'post_type'     => 'page',
        'comment_status' => 'closed',
        'ping_status' => 'closed'
    );
    
    $ins_home_id = wp_insert_post($ins_home, 10, 1);
    
    $result = $wpdb->query("SELECT wpost.post_name FROM $wpdb->posts wpost WHERE wpost.post_name = 'my-home-site'");
    
    if($result < 1){// Insert the post into the database
        do_action('wp_insert_post', 'wp_insert_post', 10, 1); 
    }
    

    .

    EDIT
    According to the Source code of wp_insert_post

    if ( empty($data['post_name']) && !in_array( $data['post_status'], array( 'draft', 'pending', 'auto-draft' ) ) ) {
        $data['post_name'] = sanitize_title($data['post_title'], $post_ID);
        $wpdb->update( $wpdb->posts, array( 'post_name' => $data['post_name'] ), $where );
    }
    

    So… if post_status not in array… post_name = post_title (sanitized ofCourse)
    So… altough i am very short on time to check it today you should try to envelope
    the ‘publish’ post_status with an aray – see my revised code

    .

    i hope this solves it… please try it and share results