How to set post slug when using wp_insert_post();?

My theme uses a custom template to render some contents. To use this template, I’m hooking into after_switch_theme to create my own page after the theme is activated, and then assign this template to it.

This is how I do it:

$new_page_title = __('Custom page');
$new_page_content="";
$new_page_template="page-custom.php";
$page_check = get_page_by_title($new_page_title);
$new_page = array(
        'post_type' => 'page',
        'post_title' => $new_page_title,
        'post_content' => $new_page_content,
        'post_status' => 'publish',
        'post_author' => 1,
        'post_slug' => 'my-custom-slug'
);
if( !isset($page_check->ID) ){
    $new_page_id = wp_insert_post($new_page);
    if(!empty($new_page_template)){
        update_post_meta($new_page_id, '_wp_page_template', $new_page_template);
    }
}

However, the page’s slug is always following the title. It means, the slug is always custom-page. Seems like wp_insert_post() doesn’t support post slug, since there isn’t any in the code reference.

I need to set the slug since the page’s title is something very popular, and there might be another page with the same slug already existing.

How can I do this?

1

The parameter to insert a custom slug is:

'post_name' => 'my-custom-slug'

Not post_slug as one would think! 🙂

Leave a Comment