Home    Articles

 

How to add custom url programmatically to a new post in Wordpress

 

Hi,

When you create a new post or page programmatically in wordpress, sometimes you want to add a custom url.

All you have to do is to add a new key=>value to the array that will be passed in wp_insert_post() function. The Key is 'post_name' and the value is a valid URL.

Here is an example:

 $post_data = array(
        'post_content' => 'Page body text',
        'post_status' => 'draft',
        'post_title' => 'Add a title here',
        'post_type' => 'page',
        'post_name'=>'some-post-custom-url'
    );
    $new_post_id = wp_insert_post( $post_data );

In order to create a valid url use preg_replace or something similar, you can find a lot of examples on the internet how to do that.

 

Enjoy.

by