Search code examples
phpwordpresswordpress-themingpermalinkscustom-wordpress-pages

How to change Wordpress' default posts permalinks programmatically?


In the backend of Wordpress I use the default http://localhost/sitename/example-post/ value for creating permalinks.

For custom post types I defined a custom slug this way, here is services for example:

register_post_type( 'service',
    array(
        'labels'      => array(
            'name'          => __( 'Services' ),
            'singular_name' => __( 'Service' )
        ),
        'public'      => true,
        'has_archive' => true,
        'rewrite'     => array(
            'slug'       => 'services',
            'with_front' => true
        ),
        'supports'    => array(
            'title',
            'editor',
            'excerpt',
            'thumbnail'
        ),
        'taxonomies'  => array( 'category' ),
    )
);

It creates services/post-name.

I also use this hook to create a custom page to create a custom page permalink:

function custom_base_rules() {
    global $wp_rewrite;

    $wp_rewrite->page_structure = $wp_rewrite->root . '/page/%pagename%/';
}

add_action( 'init', 'custom_base_rules' );

It creates page/post-name

Now the only thing I need to do is to create another custom permalink path for the normal Wordpress posts.

So the outcome world be for the post type of post:

post/post-name

I can't use the backed for this because I already defined a default way of handling the permalinks. I already managed to rewrite the paths of custom post types and pages...

How do I rewrite the normal post post type permalink path in Wordpress programmatically?


Solution

  • The permalink_structure property suggested by GentlemanMax did not work for me. But I found a method that does work, set_permalink_structure(). See code example below.

    function custom_permalinks() {
        global $wp_rewrite;
        $wp_rewrite->page_structure = $wp_rewrite->root . '/page/%pagename%/'; // custom page permalinks
        $wp_rewrite->set_permalink_structure( $wp_rewrite->root . '/post/%postname%/' ); // custom post permalinks
    }
    
    add_action( 'init', 'custom_permalinks' );