Why does wordpress keep adding postname to my CPT’s permalink in the end?

The question:

Alternate Question: How to change Permalink structure for CPT so that post name comes in the middle of URL instead of in the end eg. /a/%postname%/b/c

Any suggestions while changing the permalink structure in custom post type? Right now I want the struct to be /a/%postname%/b/c but it keeps adding postname in the end by default like /a/%postname%/b/c/%postname% .

Here’s my register_post_type code,

$args = array(
    'label' => __('testCPT', 'text_domain'),
    'description' => __('Site articles.', 'text_domain'),
    'labels' => $labels,
    'supports' => array('title', 'revisions'),
    'hierarchical' => false,
    'public' => true,
    'show_ui' => true,
    'show_in_menu' => true,
    'menu_position' => 5,
    'show_in_admin_bar' => true,
    'show_in_nav_menus' => true,
    'can_export' => true,
    'has_archive' => true,
    'exclude_from_search' => false,
    'publicly_queryable' => true,
    'rewrite' => array(
        'slug' => '/a/%postname%/b/c',
        'with_front'    => false

Structure generated:


Structure Desired:


The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

Note that you should use %<post type>% in the slug value, so if the post type is test_cpt, then you would use %test_cpt% as in /a/%test_cpt%/b/c.

And moving the post name/slug to the middle or beginning in the permalink structure is actually pretty easy:

  1. Register the post type:

    // replace test_cpt with the correct post type
    register_post_type( 'test_cpt', $args );
  2. Then after that, do this:

    global $wp_rewrite;
    // replace test_cpt with the correct post type
    $wp_rewrite->extra_permastructs['test_cpt']['struct'] = '/a/%test_cpt%/b/c';

And remember to flush the rewrite rules which can be done just by visiting the permalink settings page.

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment