18

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 Answer 1

27

The parameter to insert a custom slug is:

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

Not post_slug as one would think! :)

1
  • Note that if a post with slug exists already, wp_insert_post will create a new post with an automatically generated post_name
    – Flimm
    Jul 13, 2022 at 14:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.