Remove post type slug in custom post type URL and move subpages to website root in WordPress

I recently had a need to rewrite the URLs of all parent and child pages in a custom post type so that they appeared to live at the website root, but in reality, continued to live in a custom post type within their hierarchy.

Preface

The situation:

  1. I have a page called Services that lives at domain.com/services.
  2. I have a custom post type called Services.
  3. I have Services post called Programming that lives at domain.com/services/programming.
  4. I have Services post called Web Development, that is a child of Programming, that lives at domain.com/services/programming/web-development.

The goal:

  1. The Services page should remain where it is i.e. domain.com/services.
  2. The Programming post should appear to live at the website root i.e. domain.com/programming.
  3. The Web Development service should also live at the website root i.e. domain.com/web-development.

The reason:

  1. Shorter URLs.
  2. Keep all website pages together.
  3. Keep all services together.
  4. Maintain hierarchy of services.

Setup

I have a custom post type setup like so:

1
2
3
4
5
6
7
8
9
10
11
12
function register_services() {
    $arguments = array(
        'label' => 'Services',
        'public' => true,
        'capability_type' => 'page',
        'hierarchical' => true,
        'supports' => array('title', 'editor', 'page-attributes'),
        'has_archive' => false,
        'rewrite' => true
    );
    register_post_type('services', $arguments);
}
function register_services() {
	$arguments = array(
		'label' => 'Services',
		'public' => true,
		'capability_type' => 'page',
		'hierarchical' => true,
		'supports' => array('title', 'editor', 'page-attributes'),
		'has_archive' => false,
		'rewrite' => true
	);
	register_post_type('services', $arguments);
}

Solution

1. Remove “services” from the custom post type URL

We’re going to use the post_type_link filter to do this.

Update 1/19/14: Tweaked function to work with WordPress installed in a subdirectory.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
add_filter(
    'post_type_link',
    'custom_post_type_link',
    10,
    3
);
 
function custom_post_type_link($permalink, $post, $leavename) {
    if (!gettype($post) == 'post') {
        return $permalink;
    }
    switch ($post->post_type) {
        case 'services':
            $permalink = get_home_url() . '/' . $post->post_name . '/';
            break;
    }
 
    return $permalink;
}
add_filter(
	'post_type_link',
	'custom_post_type_link',
	10,
	3
);

function custom_post_type_link($permalink, $post, $leavename) {
    if (!gettype($post) == 'post') {
        return $permalink;
    }
    switch ($post->post_type) {
        case 'services':
            $permalink = get_home_url() . '/' . $post->post_name . '/';
            break;
    }

    return $permalink;
}
  • Line 9: If $post is a valid post object.
  • Line 13: If post belongs to a post type that we want to remove the post type slug from.
  • Line 15: Build a new permalink from home URL with just the post name.

All of this will essentially give us URLs like this:

  • domain.com/programming/
  • domain.com/web-development/

But neither of those will work – you’ll get a 404 error – because WordPress can no longer identify those posts as Services posts and therefore attempts to find pages called Programming and Web Development, which don’t exist, hence the 404 error.

If you take a look at WordPress’ rewrite rules:

1
echo '<pre>' . print_r(get_option('rewrite_rules'), true) . '</pre>';
echo '<pre>' . print_r(get_option('rewrite_rules'), true) . '</pre>';

You’ll see something similar to this:

1
2
3
4
5
Array
(
    [services/(.+?)(/[0-9]+)?/?$] => index.php?services=$matches[1]&page=$matches[2]
    [(.?.+?)(/[0-9]+)?/?$] => index.php?pagename=$matches[1]&page=$matches[2]
)
Array
(
	[services/(.+?)(/[0-9]+)?/?$] => index.php?services=$matches[1]&page=$matches[2]
	[(.?.+?)(/[0-9]+)?/?$] => index.php?pagename=$matches[1]&page=$matches[2]
)

As you can see, using the services slug, WordPress knows to take whatever comes after it ((.+?)) and pass it in as the pagename value ($matches[1]), which translates to something like:

domain.com/index.php?services=programming

Since the first rewrite rule no longer applies (slug removed), it now passes programming in as the pagename without specifying the post type, and since this page doesn’t exist, WordPress can’t return the page.

2. Add post type back to the post query

Now that WordPress doesn’t know that it’s dealing with a custom post type, we need to provide it with this information. For that we’re going to use the pre_get_posts hook.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
add_action(
    'pre_get_posts',
    'custom_pre_get_posts'
);
 
function custom_pre_get_posts($query) {
    global $wpdb;
 
    if(!$query->is_main_query()) {
        return;
    }
 
    $post_name = $query->get('pagename');
 
    $post_type = $wpdb->get_var(
        $wpdb->prepare(
            'SELECT post_type FROM ' . $wpdb->posts . ' WHERE post_name = %s LIMIT 1',
            $post_name
        )
    );
 
    switch($post_type) {
        case 'services':
            $query->set('services', $post_name);
            $query->set('post_type', $post_type);
            $query->is_single = true;
            $query->is_page = false;
            break;
    }
}
add_action(
	'pre_get_posts',
	'custom_pre_get_posts'
);

function custom_pre_get_posts($query) {
    global $wpdb;

    if(!$query->is_main_query()) {
	    return;
    }

    $post_name = $query->get('pagename');

    $post_type = $wpdb->get_var(
    	$wpdb->prepare(
    		'SELECT post_type FROM ' . $wpdb->posts . ' WHERE post_name = %s LIMIT 1',
    		$post_name
    	)
    );

    switch($post_type) {
	    case 'services':
	    	$query->set('services', $post_name);
	    	$query->set('post_type', $post_type);
	    	$query->is_single = true;
	    	$query->is_page = false;
	    	break;
    }
}
  • Line 7: We’ll need the WordPress database object to get additional information about the post.
  • Line 9-11: We’re going to make sure that the current query is the main query. Since a page can have multiple queries, we’re limiting our filter to only the query that gets information about the page itself.
  • Line 13: We’re going to grab the pagename from the query, which might be programming or web-development.
  • Line 15-20: Now we’re going to use the pagename to look in the database for that particular post and extract its post type.
  • Line 22-23: If this post has a post type that we know we need to manipulate, we’ll need to perform additional actions.
  • Line 24: We need to a create a query var for the post type and set it to the pagename, so WordPress knows where to actually find the data for the post.
  • Line 25: We also need to set the post_type back to services.
  • Line 26: In order for WordPress to load the right template i.e. single-services.php, we need to set is_single to true.
  • Line 27: Last, but not least, we set is_page to false for good measure, since it’s a custom post type.

Update 9/20/13: Changed add_filter('pre_get_posts', 'custom_pre_get_posts'); to add_action('pre_get_posts', 'custom_pre_get_posts');

Update: 12/23/14: As of WordPress 4.0, the code above doesn’t work. The following changes need to be made:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
$result = $wpdb->get_row(
    $wpdb->prepare(
        'SELECT wpp1.post_type, wpp2.post_name AS parent_post_name FROM ' . $wpdb->posts . ' as wpp1 LEFT JOIN ' . $wpdb->posts . ' as wpp2 ON wpp1.post_parent = wpp2.ID WHERE wpp1.post_name = %s LIMIT 1',
        $post_name
    )
);
 
switch($post_type) {
    case 'services':
        if ($result->parent_post_name !== '') {
            $post_name = $result->parent_post_name . '/' . $post_name;
        }
        $query->set('services', $post_name);
        $query->set('post_type', $post_type);
        $query->is_single = true;
        $query->is_page = false;
        break;
}
$result = $wpdb->get_row(
	$wpdb->prepare(
		'SELECT wpp1.post_type, wpp2.post_name AS parent_post_name FROM ' . $wpdb->posts . ' as wpp1 LEFT JOIN ' . $wpdb->posts . ' as wpp2 ON wpp1.post_parent = wpp2.ID WHERE wpp1.post_name = %s LIMIT 1',
		$post_name
	)
);

switch($post_type) {
	case 'services':
		if ($result->parent_post_name !== '') {
			$post_name = $result->parent_post_name . '/' . $post_name;
		}
		$query->set('services', $post_name);
		$query->set('post_type', $post_type);
		$query->is_single = true;
		$query->is_page = false;
		break;
}

Result

You’ve met all your goals. In addition, if you try to create a page with the same name as one of your services, you’ll notice that the slug (i.e. post_name, pagename, etc.) will now increment, avoiding a possible collision.

Here are a couple of things to keep in mind:

  1. I didn’t test the performance of this yet, but if you use some kind of caching system on your website, you should be fine.
  2. All my functions live within a PHP namespace, so I only prefixed them with custom_ for simplicity of this post.
  3. I’ve looked at many different solutions online, and they all had their fair share of problems, so this may too, I just don’t know it yet 🙂

If you have questions or suggestions, leave them in the comments below.

90 thoughts on “Remove post type slug in custom post type URL and move subpages to website root in WordPress

  1. Tristan C

    Thanks for the post! Unfortunately I can’t get it to work… I keep on getting 404s. Have tried updating the permalinks, flush_rewrite_rules();, etc.

    Reply
    1. Ryan Post author

      First, I would output the current WordPress rewrite rules (example in post), just to make sure the ones you added are indeed active. Second, I would print out the $query variable (print_r($query, true)) in custom_pre_get_posts to see that the values are set to what you expect (and also make sure the code in the filter is executed).

      Reply
  2. Marco Panichi

    Hi Ryanm thank you very much for this article. I’m going mad with this slug!!! I’ve tried your solution but it doesn’t work. Maybe you can help me – I have this situation:

    – a custom type called “static”
    – it’s hierarchical
    – my permalink structure is: “/blog/%postname%”
    – WordPress 3.5.2

    Following your instruction everything works in admin side: I can create a “static” page called “My Page Title” and the permalink in the editor becomes “http://www.—.com/my-page-title”

    Unfortunally, in the website I can reach this page only with the URL “http://www.—.com/blog/static/my-page-title”

    I have tryed lots of solutions for DAYS!

    Reply
  3. GG

    Man… as much as I want this to work its just not happening.

    I’m trying to use this in combination with 301 redirects to create a short urls post type.
    I didnt have the postype setup to begin with, so it took a minute to figure out I needed to add: add_action( 'init', 'register_services' ); May want to note this in the post.

    Also, setting has_archive to true automatically adds it to your permalink structure, you show false.

    My custom permalink structure is set to: /blog/%postname%/
    So I was getting /blog/posttype/postname/
    Shouldnt have mattered because you’re grabbing the last part of the path, but I think something was screwy there because when I print $post_name later in custom_pre_get_posts, it wasn’t finding anything.

    Last resort, i think ill use http://wordpress.org/plugins/custom-permalinks/ and change them manually.
    Thanks for trying though! Glad it worked for you.

    Reply
    1. Ryan Post author

      Let’s systematically troubleshoot this. For step #1, let’s confirm the post_type_link filter is working. If you go anywhere in your template and use get_permalink($id), with $id belonging to a services post, please provide the absolute path it printed out (you can omit the domain).

      Reply
  4. David

    To get this to work I had to change: $query->set('services', $post_name);
    to: $query->set('name', $post_name);

    Reply
  5. kevin

    What are your thoughts about getting things running with WPMU, as of right now it would default the URL back to domain.com/services/ rather than domain.com/username/services/

    Cheers
    kc

    Reply
    1. Ryan Post author

      You have a couple options. (1) You could wrap the filters in a is_main_site() check, which would only apply it to your main site, leaving your child sites as-is. (2) In step 1, where you remove the “services” slug, you could perform a is_multisite() check and then parse $post_path accordingly, essentially accounting for the site name by keeping it in there or putting it back.

      Reply
    1. Ryan Post author

      I do have MU enabled on the site that I did this on, however, I’m only applying this code on the main site and not child sites, since don’t need it (yet). Looking at the code above, there is nothing to suggest that it wouldn’t work, except for, as Kevin pointed out, you may have to adjust the $permalink that’s created in step #1 when MU is installed as sub-directories instead of sub-domains, since there’ll be an extra component in the URL that needs to be accounted for.

      Reply
  6. Stefan

    Ryan, your tutorial was very useful. My case was similar to yours and I was able to remove the slug. But I made a few modifications for this to work as you can see here https://gist.github.com/stefanbc/6620151. First of all, this line

    1
    
    add_filter('pre_get_posts','custom_pre_get_posts');
    add_filter('pre_get_posts','custom_pre_get_posts');

    should be something like this

    1
    
    add_action('pre_get_posts','custom_pre_get_posts');
    add_action('pre_get_posts','custom_pre_get_posts');

    because according to the WordPress codex there is no filter pre_get_posts
    And another thing I modified was this

    1
    
    $post_name = $query->get('pagename');
    $post_name = $query->get('pagename');

    to this

    1
    
    $post_name = $query->get('name');
    $post_name = $query->get('name');

    This was my case. Thanks for the awesome tutorial.

    Reply
    1. Ryan Post author

      Thanks for the feedback, Stefan. You are right about it being an action and not a filter. I’ve updated my post above. With regard to `pagename` vs `name`, if your custom post type is based on a post, which is the default, `name` would be in fact the way to go, but if it’s based on a page, I think `pagename` is recommended. I’m actually using it as a page, but omitted that in my setup– thanks for catching that!

      Reply
    2. Dennis

      @stefan

      Your github code worked except that it was throwing a php error regarding variables. I changed:

      $post_name = end(explode('/', trim($post_path, '/')));

      to

      $path_base = explode( get_template(), str_replace( '\\', '/', dirname( __FILE__ ) ) );
      $post_name = ltrim( end( $path_base ), '/' );

      and it worked beautifully.

      Thanks

      Reply
  7. chụp ảnh cưới

    I using

    [product-category/(.+?)/feed/(feed|rdf|rss|rss2|atom)/?$] => index.php?product_cat=$matches[1]&feed=$matches[2]
    [product-category/(.+?)/(feed|rdf|rss|rss2|atom)/?$] => index.php?product_cat=$matches[1]&feed=$matches[2]
    [product-category/(.+?)/page/?([0-9]{1,})/?$] => index.php?product_cat=$matches[1]&paged=$matches[2]
    [product-category/(.+?)/?$] => index.php?product_cat=$matches[1]
    [product-tag/([^/]+)/feed/(feed|rdf|rss|rss2|atom)/?$] => index.php?product_tag=$matches[1]&feed=$matches[2]
    [product-tag/([^/]+)/(feed|rdf|rss|rss2|atom)/?$] => index.php?product_tag=$matches[1]&feed=$matches[2]
    [product-tag/([^/]+)/page/?([0-9]{1,})/?$] => index.php?product_tag=$matches[1]&paged=$matches[2]
    [product-tag/([^/]+)/?$] => index.php?product_tag=$matches[1]

    with htaccess?

    Reply
    1. Ryan Post author

      The rewrite rules I showed were only a subset of those in the system to explain that particular point. What you have works just as well.

      Reply
  8. Victor

    here is how i did:
    register_post_type with these args
    'rewrite' = array('slug' => '/','with_front' => false)
    'capability_type' => 'page'

    using this approach there is no need to use post_type_link filter
    then comes custom_pre_get_posts

    Reply
  9. Bill

    Great article. THis seems to work for me on my sandbox site except one thing….
    I have a main wordpress website at http://www.website.com, but I have an additonal wordpress install in a folder of the main website….so in other words, I have my live site here:
    http://www.website-name.com
    but I installed another wordpress install in a folder I named DEMSO off that live site I use for sandbox stuff.
    http://www.website-name.com/demos/SANDBOX-SITE

    I never have any problems, however when I am trying to use this code on the sandbox site, when I view the custom post type, it takes me back to the root wordpress install, so instead of the custom post type url being
    http://www.website-name.com/demos/SANDBOX-SITE/post-name (the CPT slug is gone…yeah!!)
    it is
    http://www.website-name.com/post-name

    Can you recommend the code alteration so it doesnt strip it all the way back to the main website root, and instead takes it back to that particular wordpress install’s root?

    http://www.website-name/demos/

    Reply
    1. Ryan Sechrest Post author

      Bill, I revised the function to be a little more flexible and it should also now work with WordPress installed in a subdirectory. Take another look at the code in step 1.

      Reply
      1. Bill

        Thanks for the reply Ryan. I must be doing something wrong, because I cant get it to work. First, in step 1, you forgot the word custom in the function. Line 8 should be:
        function custom_post_type_link($permalink, $post, $leavename) {

        But regardless, I tried this but it didnt work. Not sure if this matters or not, but the site is located in this path
        public_html/SUBFOLDER/the-wordpress-install-is-here

        The custom post type name is “neighborhoods”. Here is my code:

        /* Remove the neighborhoods slug from published post permalinks. Only affect our CPT though*/
        add_filter(
          'post_type_link',
          'custom_post_type_link',
          10,
          3
        );
         
        function custom_post_type_link($permalink, $post, $leavename) {
            if(is_object($post) && property_exists($post, 'post_type')) {
                switch($post->post_type) {
                    case 'neighborhoods':
                        $permalink = str_replace('/' . $post->post_type, '', $permalink);
                        break;
                }
            }
         
            return $permalink;
        }
        /*
         * Some hackery to have WordPress match postname to any of our public post types
         * All of our public post types can have /post-name/ as the slug, so they better be unique across all posts
         * Typically core only accounts for posts and pages where the slug is /post-name/
         */
        add_action(
          'pre_get_posts',
          'custom_pre_get_posts'
        );
         
        function custom_pre_get_posts($query) {
            global $wpdb;
         
            if(!$query->is_main_query()) {
              return;
            }
         
            $post_name = $query->get('pagename');
         
            $post_type = $wpdb->get_var(
              $wpdb->prepare(
                'SELECT post_type FROM ' . $wpdb->posts . ' WHERE post_name = %s LIMIT 1',
                $post_name
              )
            );
         
            switch($post_type) {
              case 'neighborhoods':
                $query->set('neighborhoods', $post_name);
                $query->set('post_type', $post_type);
                $query->is_single = true;
                $query->is_page = false;
                break;
            }
         
            return $query;
        }
        Reply
  10. Bill

    Hi Ryan…
    Ok, I tried new code …the permalink does change int he editor screen …the slug is not there, but I get the 404. I tried resetting permalinks just to make sure there wasn’t an issue there with the 404, but still no dice.
    I will paste what I have below for the CPT just in case it is something on my end…

    /** Remove slug from custom post type for "neighborhoods" custom post ype */
    add_filter(
      'post_type_link',
      'custom_post_type_link',
      10,
      3
    );
     
    function custom_post_type_link($permalink, $post, $leavename) {
        if (!gettype($post) == 'post') {
            return $permalink;
        }
        switch ($post->post_type) {
            case 'neighborhoods':
                $permalink = get_home_url() . '/' . $post->post_name . '/';
                break;
     
        }
     
        return $permalink;
    }
    
    /*
     * Some hackery to have WordPress match postname to any of our public post types
     * All of our public post types can have /post-name/ as the slug, so they better be unique across all posts
     * Typically core only accounts for posts and pages where the slug is /post-name/
     */
    add_action(
      'pre_get_posts',
      'custom_pre_get_posts'
    );
     
    function custom_pre_get_posts($query) {
        global $wpdb;
     
        if(!$query->is_main_query()) {
          return;
        }
     
        $post_name = $query->get('pagename');
     
        $post_type = $wpdb->get_var(
          $wpdb->prepare(
            'SELECT post_type FROM ' . $wpdb->posts . ' WHERE post_name = %s LIMIT 1',
            $post_name
          )
        );
     
        switch($post_type) {
          case 'neighborhoods':
            $query->set('neighborhoods', $post_name);
            $query->set('post_type', $post_type);
            $query->is_single = true;
            $query->is_page = false;
            break;
        }
     
        return $query;
    }
    /*****nd this is my custom post type:******/
    
    /* Add Custom Post Type for Neighborhoods*/
    add_action( 'init', 'create_my_post_types2', 2 );
    
    function create_my_post_types2() {
    	register_post_type( 'neighborhoods', 
    		array(
    			'labels' => array(
    				'name' => __( 'Neighborhoods' ),
    				'singular_name' => __( 'neighborhoods' ),
    				'add_new' => __( 'Add New' ),
    				'add_new_item' => __( 'Add neighborhood' ),
    				'edit' => __( 'Edit' ),
    				'edit_item' => __( 'Edit neighborhood' ),
    				'new_item' => __( 'New neighborhood' ),
    				'view' => __( 'View neighborhood' ),
    				'view_item' => __( 'View neighborhood' ),
    				'search_items' => __( 'Search neighborhoods' ),
    				'not_found' => __( 'No neighborhoods found' ),
    				'not_found_in_trash' => __( 'No neighborhoods found in Trash' ),
    				'parent' => __( 'Parent neighborhoods' ),
    			),
    				'public' => true,
    				'show_ui' => true,
    				'publicly_queryable' => true,
    				'exclude_from_search' => false,
    				'menu_position' => 20,
    				'menu_icon' => get_stylesheet_directory_uri() . '/images/neighborhood-icon.png',
    				'hierarchical' => false,
    				'query_var' => false,
    				'supports' => array( 'title', 'editor', 'excerpt', 'custom-fields', 'thumbnail', 'page-attributes', 'author', 'comments' ,'genesis-layouts', 'genesis-seo' , 'trackbacks', 'revisions' ),
    				'rewrite' => array( 'slug' => 'neighborhoods', 'with_front' => false ),
    				'taxonomies' => array( 'post_tag', 'category'),
    				'has_archive' => true,
    				'can_export' => true,
    				
    		)
    	);
    }
    Reply
  11. bill

    thanks Ryan. I followed your instructions…I still get a 404 for both service posts I create (one parent and one child)

    Reply
    1. Ryan Sechrest Post author

      Maybe you have a different kind of WordPress configuration or a plugin that is preventing this from working? I downloaded WordPress 3.8, installed it in a subdirectory as a single site, and then only installed that plugin I referenced above, and that worked for me.

      As a side note, this is also working on a production site running multisite, where WordPress is in a subdirectory, but served from the root.

      The ultimate test would be to setup a clean WordPress, just to rule out a configuration/setup/plugin issue. If that works, you know it has something to do with your sandbox.

      With regard to debugging the sandbox, since the problem seems to be related to step #2 (since the URL seems to be accurate), I would start with printing out various variables. Something like:

      add_action(
      	'pre_get_posts',
      	'custom_pre_get_posts'
      );
      
      function custom_pre_get_posts($query) {
          global $wpdb;
      
          if(!$query->is_main_query()) {
      	    return;
          }
      
          echo '$query before: <pre>' . print_r($query, true) . '</pre>';
      
          $post_name = $query->get('pagename');
      
          echo '$post_name: <pre>' . $post_name . '</pre>';
      
          $post_type = $wpdb->get_var(
          	$wpdb->prepare(
          		'SELECT post_type FROM ' . $wpdb->posts . ' WHERE post_name = %s LIMIT 1',
          		$post_name
          	)
          );
      
          echo '$post_type: <pre>' . $post_type . '</pre>';
      
          switch($post_type) {
      	    case 'services':
      	    	$query->set('services', $post_name);
      	    	$query->set('post_type', $post_type);
      	    	$query->is_single = true;
      	    	$query->is_page = false;
      	    	break;
          }
      
          echo '$query after: <pre>' . print_r($query, true) . '</pre>';
      
          return $query;
      }
      Reply
  12. Bill

    Thanks for your help Ryan!
    ….I deactivated all plugins, and switched to 2014 theme…. still same issue. 404 error.

    Here is my set up: I originally had a website in the main public_html folder. Then over the years, I added three add-on domains for this hostgator account. so it was set up like this:

    public_html/MAIN WORDPRESS INSTALL/ (then I have three different folders here….one for each of the three add-on websites)

    Each of the three folders has its own WordPress install. Then a year or so ago, I deleted the main wordpress install from the server because I dont use that site anymore…. but I kept the three ass-on websites….. so it looks like this
    public_html/website1.com or
    public_html/website2.com or
    public_html/website2.com

    It’s the same public_html/ but with three different add-on domains, and the original wordpress install is not there anymore….just the addon folders. Not sure why this would make a difference, but maybe it does?

    Reply
    1. Ryan Sechrest Post author

      The individual WordPress sites (using add-on domains) should be isolated from each other, so I don’t think that’s the problem.

      Re: WordPress theme and plugin deactivation, while that is a good test, there could still be some configuration in the database that could prevent this from working. A better test would be a fresh install with a newly setup database.

      Also, have you checked the output of the variables mentioned in my previous comment?

      Reply
  13. Daniel

    Hi Ryan,

    Nice job. However I hope you can help.
    I’m wondering what if you want to replace the post type slug with my taxonomy term slug. How do I do that?

    Cheers.

    Reply
    1. Ryan Sechrest Post author

      You could try something like this. It assumes you are using the post_tag taxonomy and only have one term. If you have more than one term, it will use the first one. In addition, while the permalink will generate based on your selected term, it doesn’t validate the term when parsing the URL, meaning the page would render with any term, really.

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      
      function post_type_link($permalink, $post, $leavename) {
          if (!gettype($post) == 'post') {
              return $permalink;
          }
          
          switch ($post->post_type) {
              case 'service':
                  $permalink = get_home_url() . '/';
                  $terms = wp_get_post_terms($post->ID, 'post_tag', array('number' => 1));
                  if (is_array($terms) && isset($terms[0]) && property_exists($terms[0], 'slug')) {
                      $permalink .= $terms[0]->slug . '/';
                  }
                  $permalink .= $post->post_name . '/';
                  break;
          }
       
          return $permalink;
      }
      function post_type_link($permalink, $post, $leavename) {
      	if (!gettype($post) == 'post') {
      		return $permalink;
      	}
      	
      	switch ($post->post_type) {
      		case 'service':
      			$permalink = get_home_url() . '/';
      			$terms = wp_get_post_terms($post->ID, 'post_tag', array('number' => 1));
      			if (is_array($terms) && isset($terms[0]) && property_exists($terms[0], 'slug')) {
      				$permalink .= $terms[0]->slug . '/';
      			}
      			$permalink .= $post->post_name . '/';
      			break;
      	}
      
      	return $permalink;
      }
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      
      function pre_get_posts($query) {
          global $wpdb;
       
          if (!$query->is_main_query()) {
              return;
          }
       
          $post_name = $query->get('pagename');
       
          $last_pos = strrpos($post_name, '/');
       
          if ($last_pos !== false) {
              $post_name = substr($post_name, $last_pos + 1);
          }
       
          $post_type = $wpdb->get_var(
              $wpdb->prepare(
                  'SELECT post_type FROM ' . $wpdb->posts . ' WHERE post_name = %s LIMIT 1',
                  $post_name
              )
          );
       
          switch ($post_type) {
              case 'service':
                  if (substr_count($query->get('pagename'), '/') != 1) {
                      return $query;
                  }
                  $query->set('service', $post_name);
                  $query->set('post_type', $post_type);
                  $query->is_single = true;
                  $query->is_page = false;
                  break;
          }
       
          return $query;
      }
      function pre_get_posts($query) {
      	global $wpdb;
      
      	if (!$query->is_main_query()) {
      		return;
      	}
      
      	$post_name = $query->get('pagename');
      
      	$last_pos = strrpos($post_name, '/');
      
      	if ($last_pos !== false) {
      		$post_name = substr($post_name, $last_pos + 1);
      	}
      
      	$post_type = $wpdb->get_var(
      		$wpdb->prepare(
      			'SELECT post_type FROM ' . $wpdb->posts . ' WHERE post_name = %s LIMIT 1',
      			$post_name
      		)
      	);
      
      	switch ($post_type) {
      		case 'service':
      			if (substr_count($query->get('pagename'), '/') != 1) {
      				return $query;
      			}
      			$query->set('service', $post_name);
      			$query->set('post_type', $post_type);
      			$query->is_single = true;
      			$query->is_page = false;
      			break;
      	}
      
      	return $query;
      }
      Reply
  14. Yumna

    Hi Ryan,

    I am trying to change my cpt urls using your code. I could remove slug from parent post urls, but it fails on child post urls. My cpt is hierarchical. I modified the post_type_link hooked function as below and now it changes link for child pages as well

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    
    function custom_post_type_link($permalink, $post, $leavename) {
        if ((!gettype($post) == 'post') ){
            return $permalink;
        }
        
        switch ($post->post_type) {
            case 'user-page':
            //var_dump($post);
            if($post->post_parent!=0){
                $permalink = get_home_url() . '/' . get_post($post->post_parent)->post_title. '/'. $post->post_name ;
                }else{
                 $permalink = get_home_url() . '/' . $post->post_name . '/';
                    }
                break;
        }
     
        return $permalink;
    }
    function custom_post_type_link($permalink, $post, $leavename) {
        if ((!gettype($post) == 'post') ){
            return $permalink;
        }
        
        switch ($post->post_type) {
            case 'user-page':
            //var_dump($post);
            if($post->post_parent!=0){
                $permalink = get_home_url() . '/' . get_post($post->post_parent)->post_title. '/'. $post->post_name ;
                }else{
                 $permalink = get_home_url() . '/' . $post->post_name . '/';
                    }
                break;
        }
     
        return $permalink;
    }

    Now the permalinks are created correctly, but the problem is that i get a 404 on child posts. I have dumped the query on both parent and child posts and i have noticed that on child post, the query_var attachment is set and no other query_vars are set. Please help if possible. Thanks.

    Reply
    1. Ryan Sechrest Post author

      OK, first you’ll want to change post_title to post_name on line 10, because otherwise you might have space and capitalization issues in the URL. I’d also add the trailing slash.

      1
      
      $permalink = get_home_url() . '/' . get_post($post->post_parent)->post_name . '/' . $post->post_name . '/';
      $permalink = get_home_url() . '/' . get_post($post->post_parent)->post_name . '/' . $post->post_name . '/';

      Second, and this is the main problem, the post name being used to find your child page in the database contains the parent slug, in other words, parent-page/child-page, but there is no post with a post name like that, hence the page not found error.

      That means you have to strip out the parent slug or simply take the contents after the last slash.

      If you add the following after $post_name = $query->get('pagename'); in the pre_get_posts hook, it should work:

      1
      2
      3
      4
      5
      
      $last_pos = strrpos($post_name, '/');
       
      if ($last_pos !== false) {
          $post_name = substr($post_name, $last_pos + 1);
      }
      $last_pos = strrpos($post_name, '/');
      
      if ($last_pos !== false) {
          $post_name = substr($post_name, $last_pos + 1);
      }

      Let me know if this works.

      Reply
    1. Ryan Sechrest Post author

      I don’t think you followed my tutorial very closely, because your code looks completely different. At first glance, though, I believe you’re coming up empty here:

      if ( ! empty( $query->query['name'] ) )  {
          $query->set( 'post_type', array( 'post', 'resort', 'page' ) );
       }

      Try swapping $query->query['name'] with $query->get['pagename'].

      Reply
  15. Yana

    Hello Ryan,
    thank you for this great post, it was exactly what I am looking for.
    Just one question regarding to Tomas post if this function or plugin will work with WPML:
    I use your function for a site which is published in two languages (German source and English using WPML plugin). I have different custom post types (on of them is members, not hierarchical) which are first filled in an overview page (simple loop) including an link to the detail page of the member. The overview works as expected but when I try to get the detail page it only works in the German version, the English version throws an error 404. I would really appreciate any advise which will point me to the right direction.
    Thank you,
    Yana

    Reply
    1. Ryan Sechrest Post author

      Looking back at Tomas’ post, I didn’t even realize that he was talking about WPML the plugin and not WPMU… I skipped right over that!

      I use your function for a site which is published in two languages (German source and English using WPML plugin).

      So your main site is example.org and your translated site is something like example.org/?lang=en, right?

      I have different custom post types (on of them is members, not hierarchical)

      So member pages look something like this, right?

      * example.org/members/john-doe
      * example.org/members/jane-doe
      * example.org/members/foo-bar

      which are first filled in an overview page (simple loop) including an link to the detail page of the member

      When you say overview and detail page, do you mean something like:

      Overview: example.org/members/john-doe — Contains picture, name, basic info.
      Detail: example.org/members/john-doe/details — Contains expanded profile, posts published, etc.

      The overview works as expected but when I try to get the detail page it only works in the German version, the English version throws an error 404.

      So, this works:

      * example.org/members/john-doe
      * example.org/members/john-doe/?lang=en
      * example.org/members/john-doe/details

      But this does not:

      * example.org/members/john-doe/details/?lang=en

      Did I understand the problem correctly?

      Reply
  16. Yana

    Hello Ryan,

    thank you for your response.

    ple.org/?lang=en, right?

    No it is example.org/en and for german (source language) only example.org/

    My german overview page has this url format: myurl.com/my-page/my-subpage/sub-sub-page/ with a list of all members.

    It is a loop through the cpt (in the template file) with listing the members in this page showing their picture and small informations, including a link to their detail page.

    The english version has this url: myurl.com/en/my-page-en/my-subpage-en/sub-sub-page-en/

    What I do is using your function to remove the slug from cpt an add a new path to get the following result for the detail page in the url (german):

    myurl.com/my-page/my-subpage/sub-sub-page/john-doe

    and for the english version:

    myurl.com/en/my-page-en/my-subpage-en/sub-sub-page-en/john-doe

    I have an if statement in the function to get the current language code and use to two different path for the german and english version.

    Everything works perfect in the german version but when I try to call the detail page of e.g. myurl.com/my-page/my-subpage/sub-sub-page-en/john-doe I get the error 404.

    Thank for your help and if you need more information please let me know.

    Yana

    Reply
    1. Ryan Sechrest Post author

      You have en several times in the URL, but that’s just to indicate that it is an English slug, right? The only thing used to determine language is en right after the domain, correct?

      In other words, this works:

      myurl.com/seite/sub-seite/sub-sub-seite/john-doe

      But this does not work:

      myurl.com/en/page/sub-page/sub-sub-page/john-doe

      Did I get that right?

      If so, it seems part 1, building the URL, is working fine for you, but you’re having trouble with part 2, which is rebuilding the query to then display the resulting data.

      Reply
      1. Yana

        Hello Ryan,

        yes, exactly.
        This is working

        myurl.com/seite/sub-seite/sub-sub-seite/john-doe

        This is not working

        myurl.com/en/page/sub-page/sub-sub-page/john-doe

        Thank you
        Yana

        Reply
          1. Yana

            Here is the code I am using:

            1
            2
            3
            4
            5
            6
            7
            8
            9
            10
            11
            12
            13
            14
            15
            16
            17
            18
            19
            20
            21
            22
            23
            24
            25
            26
            
            add_filter('post_type_link', 'svr_custom_post_type_link', 10, 3);
             
            function svr_custom_post_type_link($permalink, $post, $leavename) {
                if (!gettype($post) == 'post') {
                    return $permalink;
                }
                switch ($post->post_type) {
                    case 'mitglieder-svr':
                        if (ICL_LANGUAGE_CODE == 'de') {
                            $permalink = home_url( '/' ) . 'sachverstaendigenrat/wir-ueber-uns/mitglieder-svr/' . $post->post_name . '/';
                        }
                        if (ICL_LANGUAGE_CODE == 'en') {
                            $permalink = home_url( '/' )  . 'expert-council/about-us/council-members/' . $post->post_name . '/';
                        }
                        break;
                    case 'mitarbeiter':
                        if (ICL_LANGUAGE_CODE == 'de') {
                        $permalink = home_url( '/' ) . 'sachverstaendigenrat/wir-ueber-uns/geschaeftsstelle/' . $post->post_name . '/';
                            }
                        if (ICL_LANGUAGE_CODE == 'en') {
                         $permalink =  home_url( '/' ) . 'expert-council/about-us/berlin-office/' . $post->post_name . '/';
                        }       
                        break;
                }
                return $permalink;
            }
            add_filter('post_type_link', 'svr_custom_post_type_link', 10, 3);
             
            function svr_custom_post_type_link($permalink, $post, $leavename) {
                if (!gettype($post) == 'post') {
                    return $permalink;
                }
                switch ($post->post_type) {
                    case 'mitglieder-svr':
            			if (ICL_LANGUAGE_CODE == 'de') {
            	            $permalink = home_url( '/' ) . 'sachverstaendigenrat/wir-ueber-uns/mitglieder-svr/' . $post->post_name . '/';
            			}
            			if (ICL_LANGUAGE_CODE == 'en') {
            	            $permalink = home_url( '/' )  . 'expert-council/about-us/council-members/' . $post->post_name . '/';
            			}
                        break;
            		case 'mitarbeiter':
            			if (ICL_LANGUAGE_CODE == 'de') {
                        $permalink = home_url( '/' ) . 'sachverstaendigenrat/wir-ueber-uns/geschaeftsstelle/' . $post->post_name . '/';
            				}
            			if (ICL_LANGUAGE_CODE == 'en') {
            			 $permalink =  home_url( '/' ) . 'expert-council/about-us/berlin-office/' . $post->post_name . '/';
            			}    	
                        break;
                }
                return $permalink;
            }

            And the pre_get_post functions look like this:

            1
            2
            3
            4
            5
            6
            7
            8
            9
            10
            11
            12
            13
            14
            15
            16
            17
            18
            19
            20
            21
            22
            23
            24
            25
            26
            27
            28
            29
            30
            31
            32
            33
            34
            35
            36
            37
            38
            39
            40
            41
            42
            43
            44
            45
            46
            47
            48
            49
            
            add_action('pre_get_posts', 'svr_custom_pre_get_posts');
             
            function svr_custom_pre_get_posts($query) {
                global $wpdb;
             
                if(!$query->is_main_query()) {
                    return;
                }
                
             
                $post_name = $query->get('name');
             
             
             $result = $wpdb->get_row(
                $wpdb->prepare(
                    'SELECT wpp1.post_type, wpp2.post_name AS parent_post_name FROM ' . $wpdb->posts . ' as wpp1 LEFT JOIN ' . $wpdb->posts . ' as wpp2 ON wpp1.post_parent = wpp2.ID WHERE wpp1.post_name = %s LIMIT 1',
                    $post_name
                )
            );
             
            if(!empty($result->post_type)) {
             
                switch($result->post_type) {
                    
                    case 'mitglieder-svr':
                        if ($result->parent_post_name !== '') {
                            $post_name = $result->parent_post_name . '/' . $post_name;
                        }
                        $query->set('mitglieder-svr', $post_name);
                        $query->set('post_type', $result->post_type);
                        $query->is_single = true;
                        $query->is_page = false;
                        break;
             
                    case 'mitarbeiter':
                        if ($result->parent_post_name !== '') {
                            $post_name = $result->parent_post_name . '/' . $post_name;
                        }
                        $query->set('mitarbeiter', $post_name);
                        $query->set('post_type', $result->post_type);
                        $query->is_single = true;
                        $query->is_page = false;
                        break;
             
                }
            }
             
                return $query;
            }
            add_action('pre_get_posts', 'svr_custom_pre_get_posts');
             
            function svr_custom_pre_get_posts($query) {
                global $wpdb;
             
                if(!$query->is_main_query()) {
                    return;
                }
            	
             
                $post_name = $query->get('name');
            
             
             $result = $wpdb->get_row(
            	$wpdb->prepare(
            		'SELECT wpp1.post_type, wpp2.post_name AS parent_post_name FROM ' . $wpdb->posts . ' as wpp1 LEFT JOIN ' . $wpdb->posts . ' as wpp2 ON wpp1.post_parent = wpp2.ID WHERE wpp1.post_name = %s LIMIT 1',
            		$post_name
            	)
            );
            
            if(!empty($result->post_type)) {
            
            	switch($result->post_type) {
            		
            		case 'mitglieder-svr':
            			if ($result->parent_post_name !== '') {
            	    		$post_name = $result->parent_post_name . '/' . $post_name;
            	    	}
                        $query->set('mitglieder-svr', $post_name);
                        $query->set('post_type', $result->post_type);
                        $query->is_single = true;
                        $query->is_page = false;
                        break;
            
            	    case 'mitarbeiter':
            	    	if ($result->parent_post_name !== '') {
            	    		$post_name = $result->parent_post_name . '/' . $post_name;
            	    	}
            	    	$query->set('mitarbeiter', $post_name);
            	    	$query->set('post_type', $result->post_type);
            	    	$query->is_single = true;
            	    	$query->is_page = false;
            	    	break;
            
                }
            }
             
                return $query;
            }

            It seems that the first function causes also an error in the backend, all page, post and cpt linstings disappeared this morning. By removing the function everthing works again.

  17. Ryan Sechrest Post author

    @Yana

    Can you print out $result on a German and an English error page? You can do that with something like:

    echo '<pre>' . print_r($result, true) . '</pre>';

    It seems that the first function causes also an error in the backend, all page, post and cpt linstings disappeared this morning. By removing the function everthing works again.

    Do you know what the error was?

    Reply
    1. Yana

      I was wrong, it is not the first function, it is the pre_get_post function which causes the problem. After cache clearing the whole site throws an 404 error. It seems that in my case the first cpt mitglieder-svr is allways used in every query.

      stdClass Object
      (
          [post_type] => mitglieder-svr
          [parent_post_name] => 
      )
      Reply
      1. Ryan Sechrest Post author

        Give the original code a try for pre_get_posts (especially the query part that gets the post type), since you are not exactly doing what I’m doing in the blog post (which is writing all permalinks to the root without the post type slug.

        Reply
  18. Trieu To

    Hi Ryan

    I use your code but at step 2 it not working.

    This is my code:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    
    function custom_pre_get_posts($query) {
        global $wpdb;
     
        if(!$query->is_main_query()) {
          return;
        }
     
        $post_name = $query->get('pagename');
        $result = $wpdb->get_row(
        $wpdb->prepare(
            'SELECT wpp1.post_type, wpp2.post_name AS parent_post_name FROM ' . $wpdb->posts . ' as wpp1 LEFT JOIN ' . $wpdb->posts . ' as wpp2 ON wpp1.post_parent = wpp2.ID WHERE wpp1.post_name = %s LIMIT 1',
            $post_name
        )
    );
     
    if(!empty($result->post_type)) {
     
        switch($result->post_type) {
     
            case 'chapter':
                if ($result->parent_post_name !== '') {
                    $post_name = $result->parent_post_name . '/' . $post_name;
                }
                $query->set('chapter', $post_name);
                $query->set('post_type', $result->post_type);
                $query->is_single = true;
                $query->is_page = false;
                break;
     
        }
    }
        return $query;
    }
    function custom_pre_get_posts($query) {
        global $wpdb;
     
        if(!$query->is_main_query()) {
          return;
        }
     
        $post_name = $query->get('pagename');
     	$result = $wpdb->get_row(
    	$wpdb->prepare(
    		'SELECT wpp1.post_type, wpp2.post_name AS parent_post_name FROM ' . $wpdb->posts . ' as wpp1 LEFT JOIN ' . $wpdb->posts . ' as wpp2 ON wpp1.post_parent = wpp2.ID WHERE wpp1.post_name = %s LIMIT 1',
    		$post_name
    	)
    );
    
    if(!empty($result->post_type)) {
    
    	switch($result->post_type) {
    
    	    case 'chapter':
    	    	if ($result->parent_post_name !== '') {
    	    		$post_name = $result->parent_post_name . '/' . $post_name;
    	    	}
    	    	$query->set('chapter', $post_name);
    	    	$query->set('post_type', $result->post_type);
    	    	$query->is_single = true;
    	    	$query->is_page = false;
    	    	break;
    
        }
    }
        return $query;
    }
    Reply
  19. Trieu To

    Dear Ryan

    I want to few character to url example:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    
    add_filter(
        'post_type_link',
        'custom_post_type_link',
        10,
        3
    );
     
    function custom_post_type_link($permalink, $post, $leavename) {
        if (!gettype($post) == 'post') {
            return $permalink;
        }
        switch ($post->post_type) {
            case 'services':
                $permalink = get_home_url() . '/' .'example'. $post->post_name . '/';
                break;
        }
     
        return $permalink;
    }
    add_filter(
        'post_type_link',
        'custom_post_type_link',
        10,
        3
    );
     
    function custom_post_type_link($permalink, $post, $leavename) {
        if (!gettype($post) == 'post') {
            return $permalink;
        }
        switch ($post->post_type) {
            case 'services':
                $permalink = get_home_url() . '/' .'example'. $post->post_name . '/';
                break;
        }
     
        return $permalink;
    }

    But step 2 not work. How can i fix it? and How can i add any character to my custom post type slug?

    Reply
    1. Ryan Sechrest Post author

      Let’s say your post name is “foobar” and let’s say you build a URL as follows:

      example.org/examplefoobar

      When the query is performed to look up the post, there is no post in your database called “examplefoobar,” which is why step 2 is not working.

      If you are adding “example” in the post name, you must remove it again prior to making the query. So, on line 8 in your first post, you could try something like this:

      $post_name = str_replace('example', '', $query->get('pagename'));

      Note that in this case, regardless of where “example” occurs in the string, it will be removed, so depending on your rules, you may want to refine it.

      Better yet, though, if you changed it to example/foobar instead of examplefoobar, that might be a little bit more reliable, as you could just grab everything after the last slash, but at that point, you might as well just change the slug of the post type to example, because then you don’t need any of this extra code.

      You can find this argument in the rewrite section on the register_post_type page in the WordPress codex.

      1
      2
      3
      4
      5
      6
      7
      
      $args = array(
          'rewrite' => array(
              'slug' => 'example'
          )
      );
       
      register_post_type('something', $args);
      $args = array(
      	'rewrite' => array(
      		'slug' => 'example'
      	)
      );
      
      register_post_type('something', $args);
      Reply
  20. Teilmann

    Hello Ryan,

    I have implemented your solution on my local environment, and it works like a charm. However, when i do the same on the online solution, some links break, and i cannot save stuff in the administration panel. (posts, permalinks and more). Any thoughts?

    Reply
    1. Teilmann

      Nevermind Ryan, i seemed to fix the problem. The former programmer on the site im working on, made a bunch of whitespaces in the online version of the functions.php file, which caused the white screen of death. 🙂 thanks for the awesome solution

      Reply
        1. Thomas Teilmann

          Hello again, it seems i have found yet another problem :/

          When i implemented your solution, i changed the permalinks to some of my custom post types, so that they linked to the root of the website. By doing that, i now have more than one link to my custom post types. The links i had before i changed it, is still active, and thats not good according to google (SEO), because the pages are interpreted as duplicates (obviously).

          Any idea how to fix this?

          Reply
  21. Pierre

    Hi ryan, Trying to use your solution to remove “product” from slug in woocommerce

    But the query in get is quite empty (at least for name and pagename) , and i got 404.

        'name' => '',
        'static' => '',
        'pagename' => '',

    This is the code, in case you spot any issue…

    Reply
  22. Colir

    Yo Ryan
    i’ve spent time on the problem and here is what happen :
    – i can’t get the post type in the pre_get_posts function because after apply the post_type_link filter,
    $post_name = $page_name = $query->get('pagename'); is empty.

    So here is what i’m done. this work but it’s really tricky

    function remove_cpt_slug( $permalink, $post, $leavename ) {
        if ( 'galerie' != $post->post_type || 'publish' != $post->post_status ) {
            return $post_link;
       		}
    	   $permalink = str_replace($post->post_type . '/', '', $permalink);
        return $permalink;
    }
    add_filter( 'post_type_link', 'remove_cpt_slug', 10, 3 );
    
    function pre_get_posts( $query ) {
    	global $wp_query;
    	
        if ( ! $query->is_main_query())
            return;
    
    	$post_name = $page_name = $query->get('pagename');
    	$page_id = $query->get('page_id');
    	
        if (  empty( $page_name ) && $page_id == 0) {
            $query->set( 'post_type', 'galerie'  );
    		$query->is_single = true;
            $query->is_page = false;
        }
    }
    add_action( 'pre_get_posts', 'pre_get_posts' );

    note: i also test the $page_id, because my home page is a custom template page.
    on this page (home), the $post_name is also empty, but not his ID.

    How to you think we can improve the things ?
    thanks

    Reply
    1. Ryan Sechrest Post author

      Hi Colir,

      Print out $query in pre_get_posts using something like:

      wp_die('<pre>'.print_r($query, true).'</pre>');

      And let me know what the result is.

      You need to obtain the post type, otherwise your hook will fire on every request and for all post types, which will most likely break other aspects of WordPress.

      Also, just to confirm, are you running the latest version of WordPress? I tested this with version 4.3.1 and a non-multisite install.

      Reply
      1. Colir

        Here is the result.
        For info, my child post name is CEP.
        As you can see the query let appear it as an attachment, but i didn’t know why (this is not the case if didnt filter the permalink).
        My WP version is 4.3.1

        WP_Query Object
        (
            [query_vars] => Array
                (
                    [attachment] => cep
                    [error] => 
                    [m] => 
                    [p] => 0
                    [post_parent] => 
                    [subpost] => 
                    [subpost_id] => 
                    [attachment_id] => 0
                    [name] => 
                    [static] => 
                    [pagename] => 
                    [page_id] => 0
                    [second] => 
                    [minute] => 
                    [hour] => 
                    [day] => 0
                    [monthnum] => 0
                    [year] => 0
                    [w] => 0
                    [category_name] => 
                    [tag] => 
                    [cat] => 
                    [tag_id] => 
                    [author] => 
                    [author_name] => 
                    [feed] => 
                    [tb] => 
                    [paged] => 0
                    [comments_popup] => 
                    [meta_key] => 
                    [meta_value] => 
                    [preview] => 
                    [s] => 
                    [sentence] => 
                    [fields] => 
                    [menu_order] => 
                    [category__in] => Array
                        (
                        )
        
                    [category__not_in] => Array
                        (
                        )
        
                    [category__and] => Array
                        (
                        )
        
                    [post__in] => Array
                        (
                        )
        
                    [post__not_in] => Array
                        (
                        )
        
                    [tag__in] => Array
                        (
                        )
        
                    [tag__not_in] => Array
                        (
                        )
        
                    [tag__and] => Array
                        (
                        )
        
                    [tag_slug__in] => Array
                        (
                        )
        
                    [tag_slug__and] => Array
                        (
                        )
        
                    [post_parent__in] => Array
                        (
                        )
        
                    [post_parent__not_in] => Array
                        (
                        )
        
                    [author__in] => Array
                        (
                        )
        
                    [author__not_in] => Array
                        (
                        )
        
                )
        
            [tax_query] => 
            [meta_query] => 
            [date_query] => 
            [post_count] => 0
            [current_post] => -1
            [in_the_loop] => 
            [comment_count] => 0
            [current_comment] => -1
            [found_posts] => 0
            [max_num_pages] => 0
            [max_num_comment_pages] => 0
            [is_single] => 1
            [is_preview] => 
            [is_page] => 
            [is_archive] => 
            [is_date] => 
            [is_year] => 
            [is_month] => 
            [is_day] => 
            [is_time] => 
            [is_author] => 
            [is_category] => 
            [is_tag] => 
            [is_tax] => 
            [is_search] => 
            [is_feed] => 
            [is_comment_feed] => 
            [is_trackback] => 
            [is_home] => 
            [is_404] => 
            [is_comments_popup] => 
            [is_paged] => 
            [is_admin] => 
            [is_attachment] => 1
            [is_singular] => 1
            [is_robots] => 
            [is_posts_page] => 
            [is_post_type_archive] => 
            [query_vars_hash:WP_Query:private] => d5501ed18d237da795d238464d9f7e78
            [query_vars_changed:WP_Query:private] => 
            [thumbnails_cached] => 
            [stopwords:WP_Query:private] => 
            [compat_fields:WP_Query:private] => Array
                (
                    [0] => query_vars_hash
                    [1] => query_vars_changed
                )
        
            [compat_methods:WP_Query:private] => Array
                (
                    [0] => init_query_flags
                    [1] => parse_tax_query
                )
        
            [query] => Array
                (
                    [attachment] => cep
                )
        
        )
        Reply
        1. Ryan Sechrest Post author

          Hi Colir,

          I see the attachment, and that doesn’t appear to be normal. My guess is that either your theme or a plugin is responsible for that. It’s difficult to troubleshoot without having more context. I ran my code in a brand new WordPress installation, so I know there was nothing interfering there.

          That said, I would test the code in a brand new WordPress installation and then add your theme and plugins back, one by one, to isolate what might be causing this.

          Reply
  23. Colir

    Ryan, i ‘ve just setup a new clean install of the last version of WP,
    and active only one plugin ‘Custom Post Type UI’.
    I’ve setup a new cpt with the hierachie param on.

    I’ve the same result as you can see

    WP_Query Object
    (
        [query_vars] => Array
            (
                [attachment] => child-galerie
                [error] => 
                [m] => 
                [p] => 0
                [post_parent] => 
                [subpost] => 
                [subpost_id] => 
                [attachment_id] => 0
                [name] => 
                [static] => 
                [pagename] => 
                [page_id] => 0
                [second] => 
                [minute] => 
                [hour] => 
                [day] => 0
                [monthnum] => 0
                [year] => 0
                [w] => 0
                [category_name] => 
                [tag] => 
                [cat] => 
                [tag_id] => 
                [author] => 
                [author_name] => 
                [feed] => 
                [tb] => 
                [paged] => 0
                [comments_popup] => 
                [meta_key] => 
                [meta_value] => 
                [preview] => 
                [s] => 
                [sentence] => 
                [fields] => 
                [menu_order] => 
                [category__in] => Array
                    (
                    )
    
                [category__not_in] => Array
                    (
                    )
    
                [category__and] => Array
                    (
                    )
    
                [post__in] => Array
                    (
                    )
    
                [post__not_in] => Array
                    (
                    )
    
                [tag__in] => Array
                    (
                    )
    
                [tag__not_in] => Array
                    (
                    )
    
                [tag__and] => Array
                    (
                    )
    
                [tag_slug__in] => Array
                    (
                    )
    
                [tag_slug__and] => Array
                    (
                    )
    
                [post_parent__in] => Array
                    (
                    )
    
                [post_parent__not_in] => Array
                    (
                    )
    
                [author__in] => Array
                    (
                    )
    
                [author__not_in] => Array
                    (
                    )
    
            )
    
        [tax_query] => 
        [meta_query] => 
        [date_query] => 
        [post_count] => 0
        [current_post] => -1
        [in_the_loop] => 
        [comment_count] => 0
        [current_comment] => -1
        [found_posts] => 0
        [max_num_pages] => 0
        [max_num_comment_pages] => 0
        [is_single] => 1
        [is_preview] => 
        [is_page] => 
        [is_archive] => 
        [is_date] => 
        [is_year] => 
        [is_month] => 
        [is_day] => 
        [is_time] => 
        [is_author] => 
        [is_category] => 
        [is_tag] => 
        [is_tax] => 
        [is_search] => 
        [is_feed] => 
        [is_comment_feed] => 
        [is_trackback] => 
        [is_home] => 
        [is_404] => 
        [is_comments_popup] => 
        [is_paged] => 
        [is_admin] => 
        [is_attachment] => 1
        [is_singular] => 1
        [is_robots] => 
        [is_posts_page] => 
        [is_post_type_archive] => 
        [query_vars_hash:WP_Query:private] => fad285f1d17b209d7e24097fedf24639
        [query_vars_changed:WP_Query:private] => 
        [thumbnails_cached] => 
        [stopwords:WP_Query:private] => 
        [compat_fields:WP_Query:private] => Array
            (
                [0] => query_vars_hash
                [1] => query_vars_changed
            )
    
        [compat_methods:WP_Query:private] => Array
            (
                [0] => init_query_flags
                [1] => parse_tax_query
            )
    
        [query] => Array
            (
                [attachment] => child-galerie
            )
    
    )
    Reply
  24. Colir

    I’ve made a new test :
    removing custom Post Type UI and put directly your gist…same effect…
    The cpt ‘service’ is seen as an attachment

    Reply
      1. Colir

        I place it in the “pre_get_post” and i try to load
        a child page of my cpt

        function pre_get_posts($query) {
            global $wpdb;
            wp_die('<pre>'.print_r($query, true).'</pre>');
            // If current query is WordPress' main query
            if (!$query->is_main_query()) {
                return;
            }
        
            // Get page name from query
            $post_name = $page_name = $query->get('pagename');
        
            // Determine if post name contains slash
            $last_pos = strrpos($post_name, '/');
        
            // If post name contains slash, it's hierarchical
            if ($last_pos !== false) {
        
                // Extract actual post name
                $post_name = substr($post_name, $last_pos + 1);
            }
        
            // Retrieve post type based on post name
            $post_type = $wpdb->get_var(
                $wpdb->prepare(
                    'SELECT post_type FROM ' . $wpdb->posts . ' WHERE post_name = %s LIMIT 1',
                    $post_name
                )
            );
        
            // Only process specified post types
            switch ($post_type) {
                case 'service':
                    $query->set('service', $page_name);
                    $query->set('post_type', $post_type);
                    $query->is_single = true;
                    $query->is_page = false;
                    break;
            }
        
            return $query;
        }
        Reply
          1. Colir

            Hi Ryan.
            First at all thanks a lot for the timing you spending to help me.

            So it’s really stange.
            I’m also woth the twenty Fifteen theme.

            After putting the die just before $query, this work well.
            So i ‘ve donwload Custom Post Type UI, set another type and change the Git.

            After this done, any thing work as except.
            I’ve got an 404 on my custom type
            And for the cpt “Services” (which work well before), i’m falling with the ‘attachment problem’ even if i remove the CPT plugin…

            sorry for my poor english i’m french.
            thanks a lot

  25. Colir

    Here the modified git i use

    __('Services', PS),
            'singular_name'      => __('Service', PS),
            'menu_name'          => __('Services', PS),
            'all_items'          => __('All Services', PS),
            'add_new'            => __('Add Service', PS),
            'add_new_item'       => __('Add New Service', PS),
            'edit_item'          => __('Edit Service', PS),
            'new_item'           => __('New Service', PS),
            'view_item'          => __('View Service', PS),
            'search_items'       => __('Search Services', PS),
            'not_found'          => __('No services found', PS),
            'not_found_in_trash' => __('No services found in trash', PS),
            'parent_item_colon'  => __('Parent Service', PS)
        );
        $description = __('Services', PS);
        $supports = array(
            'title',
            'editor',
            'page-attributes'
        );
        $taxonomies = array();
        $arguments = array(
            'label'         => $label,
            'labels'        => $labels,
            'description'   => $description,
            'public'        => true,
            'show_ui'       => true,
            'menu_position' => 20,
            'hierarchical'  => true,
            'supports'      => $supports,
            'taxonomies'    => $taxonomies,
            'has_archive'   => false,
            'rewrite'       => true,
            'query_var'     => true,
            'can_export'    => false
        );
        register_post_type('service', $arguments);
    }
    
    function register_post_type_galerie() {
        $label = __('Galerie', PS);
        $labels = array(
            'name'               => __('Galeries', PS),
            'singular_name'      => __('Galerie', PS),
            'menu_name'          => __('Galeries', PS),
            'all_items'          => __('All Galeries', PS),
            'add_new'            => __('Add Galerie', PS),
            'add_new_item'       => __('Add New Galerie', PS),
            'edit_item'          => __('Edit Galerie', PS),
            'new_item'           => __('New Galerie', PS),
            'view_item'          => __('View Galerie', PS),
            'search_items'       => __('Search Galeries', PS),
            'not_found'          => __('No services found', PS),
            'not_found_in_trash' => __('No services found in trash', PS),
            'parent_item_colon'  => __('Parent Galerie', PS)
        );
        $description = __('Galeries', PS);
        $supports = array(
            'title',
            'editor',
            'page-attributes'
        );
        $taxonomies = array();
        $arguments = array(
            'label'         => $label,
            'labels'        => $labels,
            'description'   => $description,
            'public'        => true,
            'show_ui'       => true,
            'menu_position' => 20,
            'hierarchical'  => true,
            'supports'      => $supports,
            'taxonomies'    => $taxonomies,
            'has_archive'   => false,
            'rewrite'       => true,
            'query_var'     => true,
            'can_export'    => false
        );
        register_post_type('galerie', $arguments);
    }
    
    /******************************************************************************/
    
    function hook_post_type_link() {
        add_filter(
            'post_type_link',
            NS . 'post_type_link',
            10,
            3
        );
    }
    
    function post_type_link($permalink, $post, $leavename) {
    
        // Remove post type slug from these post types
        $post_types = array('service','galerie');
    
        // If current post doesn't have post type listed above
        if(!in_array($post->post_type, $post_types)) {
    
            return $permalink;
        }
    
        // Remove post type slug from permalink
        $permalink = str_replace($post->post_type . '/', '', $permalink);
    
        return $permalink;
    }
    
    /*************************************************************************/
    
    function hook_pre_get_posts() {
        add_action(
            'pre_get_posts',
            NS . 'pre_get_posts'
        );
    }
    
    function pre_get_posts($query) {
        global $wpdb;
        // If current query is WordPress' main query
        if (!$query->is_main_query()) {
            return;
        }
    
        // Get page name from query
        $post_name = $page_name = $query->get('pagename');
    
        // Determine if post name contains slash
        $last_pos = strrpos($post_name, '/');
    
        // If post name contains slash, it's hierarchical
        if ($last_pos !== false) {
    
            // Extract actual post name
            $post_name = substr($post_name, $last_pos + 1);
        }
    
        // Retrieve post type based on post name
        $post_type = $wpdb->get_var(
            $wpdb->prepare(
                'SELECT post_type FROM ' . $wpdb->posts . ' WHERE post_name = %s LIMIT 1',
                $post_name
            )
        );
    
        // Only process specified post types
        switch ($post_type) {
            case 'service':
                $query->set('service', $page_name);
                $query->set('post_type', $post_type);
                $query->is_single = true;
                $query->is_page = false;
                break;
    		case 'galerie':
                $query->set('galerie', $page_name);
                $query->set('post_type', $post_type);
                $query->is_single = true;
                $query->is_page = false;
                break;
    	}
       
       wp_die('<pre>'.print_r($query, true).'</pre>');
    
        return $query;
    }
    Reply
  26. Ash Bryant

    Hi Ryan,

    I’ve been trying to get this to work and in hope to find a solution, I also came across this before yours ( http://kellenmace.com/remove-custom-post-type-slug-from-permalinks/ ) which works, but not on a multisite install it would seem ( just on the main site ), so I continued to look for help and came here. I saw that you said your solution should work on a multisite install, so I thought ‘great!’, but I’ve been trying to get this to work for a little while now, and keep getting a 404 error.

    I have a series of cpt’s that I want to do this with ( ‘excursion’, ‘hotel’, ‘offer’, ‘tour’ ), I have these setup on a multisite install of WP using subdomains. I have also got domain mapping on them, but I have tried your solution first without this active, but with no joy.

    Can you help?

    CODE

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    
    add_filter(
        'post_type_link',
        'custom_post_type_link',
        10,
        3
    );
     
    function custom_post_type_link($permalink, $post, $leavename) {
        if (!gettype($post) == 'post') {
            return $permalink;
        }
        switch ($post->post_type) {
            case 'excursion':
              $permalink = get_home_url() . '/' . $post->post_name . '/';
              break;
            case 'hotel':
              $permalink = get_home_url() . '/' . $post->post_name . '/';
              break;
            case 'offer':
              $permalink = get_home_url() . '/' . $post->post_name . '/';
              break;
            case 'tour':
              $permalink = get_home_url() . '/' . $post->post_name . '/';
              break;
        }
     
        return $permalink;
    }
     
     
    add_action(
        'pre_get_posts',
        'custom_pre_get_posts'
    );
     
    function custom_pre_get_posts($query) {
      global $wpdb;
     
      if(!$query->is_main_query()) {
          return;
      }
     
      echo '$query before: <pre>' . print_r($query, true) . '</pre>';
     
      $post_name = $query->get('pagename');
     
      echo '$post_name: <pre>' . $post_name . '</pre>';
     
      $result = $wpdb->get_row(
        $wpdb->prepare(
          'SELECT wpp1.post_type, wpp2.post_name AS parent_post_name FROM ' . $wpdb->posts . ' as wpp1 LEFT JOIN ' . $wpdb->posts . ' as wpp2 ON wpp1.post_parent = wpp2.ID WHERE wpp1.post_name = %s LIMIT 1',
          $post_name
        )
      );
     
      switch($post_type) {
        case 'excursion':
          $query->set('excursion', $post_name);
          $query->set('post_type', $post_type);
          $query->is_single = true;
          $query->is_page = false;
          break;
     
        case 'hotel':
        /*
          if ($result->parent_post_name !== '') {
              $post_name = $result->parent_post_name . '/' . $post_name;
          }
        */
          $query->set('hotel', $post_name);
          $query->set('post_type', $post_type);
          $query->is_single = true;
          $query->is_page = false;
          break;
     
        case 'offer':
          $query->set('offer', $post_name);
          $query->set('post_type', $post_type);
          $query->is_single = true;
          $query->is_page = false;
          break;
     
        case 'tour':
          $query->set('tour', $post_name);
          $query->set('post_type', $post_type);
          $query->is_single = true;
          $query->is_page = false;
          break;
      }
     
      echo '$query after: <pre>' . print_r($query, true) . '</pre>';
    }
    add_filter(
        'post_type_link',
        'custom_post_type_link',
        10,
        3
    );
    
    function custom_post_type_link($permalink, $post, $leavename) {
        if (!gettype($post) == 'post') {
            return $permalink;
        }
        switch ($post->post_type) {
            case 'excursion':
              $permalink = get_home_url() . '/' . $post->post_name . '/';
              break;
            case 'hotel':
              $permalink = get_home_url() . '/' . $post->post_name . '/';
              break;
            case 'offer':
              $permalink = get_home_url() . '/' . $post->post_name . '/';
              break;
            case 'tour':
              $permalink = get_home_url() . '/' . $post->post_name . '/';
              break;
        }
    
        return $permalink;
    }
    
    
    add_action(
        'pre_get_posts',
        'custom_pre_get_posts'
    );
    
    function custom_pre_get_posts($query) {
      global $wpdb;
    
      if(!$query->is_main_query()) {
          return;
      }
    
      echo '$query before: <pre>' . print_r($query, true) . '</pre>';
    
      $post_name = $query->get('pagename');
    
      echo '$post_name: <pre>' . $post_name . '</pre>';
    
      $result = $wpdb->get_row(
        $wpdb->prepare(
          'SELECT wpp1.post_type, wpp2.post_name AS parent_post_name FROM ' . $wpdb->posts . ' as wpp1 LEFT JOIN ' . $wpdb->posts . ' as wpp2 ON wpp1.post_parent = wpp2.ID WHERE wpp1.post_name = %s LIMIT 1',
          $post_name
        )
      );
    
      switch($post_type) {
        case 'excursion':
          $query->set('excursion', $post_name);
          $query->set('post_type', $post_type);
          $query->is_single = true;
          $query->is_page = false;
          break;
    
        case 'hotel':
        /*
          if ($result->parent_post_name !== '') {
              $post_name = $result->parent_post_name . '/' . $post_name;
          }
        */
          $query->set('hotel', $post_name);
          $query->set('post_type', $post_type);
          $query->is_single = true;
          $query->is_page = false;
          break;
    
        case 'offer':
          $query->set('offer', $post_name);
          $query->set('post_type', $post_type);
          $query->is_single = true;
          $query->is_page = false;
          break;
    
        case 'tour':
          $query->set('tour', $post_name);
          $query->set('post_type', $post_type);
          $query->is_single = true;
          $query->is_page = false;
          break;
      }
    
      echo '$query after: <pre>' . print_r($query, true) . '</pre>';
    }
    Reply
      1. Ash Bryant

        Hi Ryan,

        It doesn’t seem to work at all. On the main site the ‘custom_post_type_link’ function seems to work as the url has those parts removed. But the ‘custom_pre_get_posts’ function doesn’t seem to work as I get a 404.

        On the other sites of the install it doesn’t do anything at all, the pages load without removing the parts and therefore load as ‘normal’.

        Reply
          1. Ash Bryant

            If it helps these are my CPT & Taxonomies

            1
            2
            3
            4
            5
            6
            7
            8
            9
            10
            11
            12
            13
            14
            15
            16
            17
            18
            19
            20
            21
            22
            23
            24
            25
            26
            27
            28
            29
            30
            31
            32
            33
            34
            35
            36
            37
            38
            39
            40
            41
            42
            43
            44
            45
            46
            47
            48
            49
            50
            51
            52
            53
            54
            55
            56
            57
            58
            59
            60
            61
            62
            63
            64
            65
            66
            67
            68
            69
            70
            71
            72
            73
            74
            75
            76
            77
            78
            79
            80
            81
            82
            83
            84
            85
            86
            87
            88
            89
            90
            91
            92
            93
            94
            95
            96
            97
            98
            99
            100
            101
            102
            103
            104
            105
            106
            107
            108
            109
            110
            111
            112
            113
            114
            115
            116
            117
            118
            119
            120
            121
            122
            123
            124
            125
            126
            127
            128
            129
            130
            131
            132
            133
            134
            135
            136
            137
            138
            139
            140
            141
            142
            143
            144
            145
            146
            147
            148
            149
            150
            151
            152
            153
            154
            155
            156
            157
            158
            159
            160
            161
            162
            163
            164
            165
            166
            167
            168
            169
            170
            171
            172
            173
            174
            175
            176
            177
            178
            179
            180
            181
            182
            183
            184
            185
            186
            187
            188
            189
            190
            191
            192
            193
            194
            195
            196
            197
            198
            199
            200
            201
            202
            203
            204
            205
            206
            207
            208
            209
            210
            211
            212
            213
            214
            215
            216
            217
            218
            219
            220
            221
            222
            223
            224
            225
            226
            227
            228
            
            add_action( 'init', 'cptui_register_my_cpts' );
            function cptui_register_my_cpts() {
                $labels = array(
                    "name" => __( 'Excursions', '' ),
                    "singular_name" => __( 'Excursion', '' ),
                    "menu_name" => __( 'Excursions', '' ),
                    "all_items" => __( 'All Excursions', '' ),
                    "add_new" => __( 'Add Excursion', '' ),
                    "add_new_item" => __( 'Add New Excursion', '' ),
                    "edit" => __( 'Edit', '' ),
                    "edit_item" => __( 'Edit Excursion', '' ),
                    "new_item" => __( 'New Excursion', '' ),
                    "view" => __( 'View', '' ),
                    "view_item" => __( 'View Excursion', '' ),
                    "search_items" => __( 'Search Excursions', '' ),
                    );
             
                $args = array(
                    "label" => __( 'Excursions', '' ),
                    "labels" => $labels,
                    "description" => "Hotels also reference \'Hotels\'",
                    "public" => true,
                    "show_ui" => true,
                    "show_in_rest" => false,
                    "rest_base" => "",
                    "has_archive" => false,
                    "show_in_menu" => true,
                    "exclude_from_search" => false,
                    "capability_type" => "post",
                    "map_meta_cap" => true,
                    "hierarchical" => false,
                    "rewrite" => array( "slug" => "excursion", "with_front" => true ),
                    "query_var" => true,
                    "menu_position" => 20,"menu_icon" => "dashicons-tickets-alt",       
                    "supports" => array( "title", "comments", "revisions", "thumbnail", "page-attributes" ),        
                    "taxonomies" => array( "holiday-type" ),        
                );
                register_post_type( "excursion", $args );
             
                $labels = array(
                    "name" => __( 'Hotels', '' ),
                    "singular_name" => __( 'Hotel', '' ),
                    "menu_name" => __( 'Hotels', '' ),
                    "all_items" => __( 'All Hotels', '' ),
                    "add_new" => __( 'Add Hotel', '' ),
                    "add_new_item" => __( 'Add New Hotel', '' ),
                    "edit" => __( 'Edit', '' ),
                    "edit_item" => __( 'Edit Hotel', '' ),
                    "new_item" => __( 'New Hotel', '' ),
                    "view" => __( 'View', '' ),
                    "view_item" => __( 'View Hotel', '' ),
                    "search_items" => __( 'Search Hotels', '' ),
                    );
             
                $args = array(
                    "label" => __( 'Hotels', '' ),
                    "labels" => $labels,
                    "description" => "Hotels also reference \'Excursions\'.",
                    "public" => true,
                    "show_ui" => true,
                    "show_in_rest" => false,
                    "rest_base" => "",
                    "has_archive" => false,
                    "show_in_menu" => true,
                    "exclude_from_search" => false,
                    "capability_type" => "post",
                    "map_meta_cap" => true,
                    "hierarchical" => false,
                    "rewrite" => array( "slug" => "hotel", "with_front" => true ),
                    "query_var" => true,
                    "menu_position" => 21,"menu_icon" => "dashicons-store",     
                    "supports" => array( "title", "comments", "revisions", "thumbnail", "page-attributes" ),        
                    "taxonomies" => array( "holiday-type" ),        
                );
                register_post_type( "hotel", $args );
             
                $labels = array(
                    "name" => __( 'Offers', '' ),
                    "singular_name" => __( 'Offer', '' ),
                    "menu_name" => __( 'Offers', '' ),
                    "all_items" => __( 'All Offers', '' ),
                    "add_new" => __( 'Add Offer', '' ),
                    "add_new_item" => __( 'Add New Offer', '' ),
                    "edit" => __( 'Edit', '' ),
                    "edit_item" => __( 'Edit Offer', '' ),
                    "new_item" => __( 'New Offer', '' ),
                    "view" => __( 'View', '' ),
                    "view_item" => __( 'View Offer', '' ),
                    "search_items" => __( 'Search Offers', '' ),
                    );
             
                $args = array(
                    "label" => __( 'Offers', '' ),
                    "labels" => $labels,
                    "description" => "An \'Offer\' can be made up of Hotels & Excursions",
                    "public" => true,
                    "show_ui" => true,
                    "show_in_rest" => false,
                    "rest_base" => "",
                    "has_archive" => false,
                    "show_in_menu" => true,
                    "exclude_from_search" => false,
                    "capability_type" => "post",
                    "map_meta_cap" => true,
                    "hierarchical" => false,
                    "rewrite" => array( "slug" => "offer", "with_front" => true ),
                    "query_var" => true,
                    "menu_position" => 22,"menu_icon" => "dashicons-smiley",        
                    "supports" => array( "title", "comments", "revisions", "thumbnail", "page-attributes" ),        
                    "taxonomies" => array( "holiday-type" ),        
                );
                register_post_type( "offer", $args );
             
                $labels = array(
                    "name" => __( 'Banners', '' ),
                    "singular_name" => __( 'Banner', '' ),
                    "menu_name" => __( 'Banners', '' ),
                    "all_items" => __( 'All Banners', '' ),
                    "add_new" => __( 'Add Banner', '' ),
                    "add_new_item" => __( 'Add New Banner', '' ),
                    "edit" => __( 'Edit', '' ),
                    "edit_item" => __( 'Edit Banner', '' ),
                    "new_item" => __( 'New Banner', '' ),
                    "view" => __( 'View', '' ),
                    "view_item" => __( 'View Banner', '' ),
                    "search_items" => __( 'Search Banner', '' ),
                    );
             
                $args = array(
                    "label" => __( 'Banners', '' ),
                    "labels" => $labels,
                    "description" => "Banners shown in various locations across the website",
                    "public" => true,
                    "show_ui" => true,
                    "show_in_rest" => false,
                    "rest_base" => "",
                    "has_archive" => false,
                    "show_in_menu" => true,
                    "exclude_from_search" => false,
                    "capability_type" => "post",
                    "map_meta_cap" => true,
                    "hierarchical" => false,
                    "rewrite" => array( "slug" => "banner", "with_front" => true ),
                    "query_var" => true,
                    "menu_icon" => "dashicons-welcome-widgets-menus",       
                    "supports" => array( "title" ),     
                    "taxonomies" => array( "banner-locations" ),        
                );
                register_post_type( "banner", $args );
             
                $labels = array(
                    "name" => __( 'Tours', '' ),
                    "singular_name" => __( 'Tour', '' ),
                    "menu_name" => __( 'Tours', '' ),
                    "all_items" => __( 'All Tours', '' ),
                    "add_new" => __( 'Add New', '' ),
                    "add_new_item" => __( 'Add New Tour', '' ),
                    "edit" => __( 'Edit', '' ),
                    "edit_item" => __( 'Edit Tour', '' ),
                    "new_item" => __( 'New Tour', '' ),
                    "view" => __( 'View', '' ),
                    "view_item" => __( 'View Tour', '' ),
                    "search_items" => __( 'Search Tours', '' ),
                    );
             
                $args = array(
                    "label" => __( 'Tours', '' ),
                    "labels" => $labels,
                    "description" => "",
                    "public" => true,
                    "show_ui" => true,
                    "show_in_rest" => false,
                    "rest_base" => "",
                    "has_archive" => false,
                    "show_in_menu" => true,
                    "exclude_from_search" => false,
                    "capability_type" => "post",
                    "map_meta_cap" => true,
                    "hierarchical" => true,
                    "rewrite" => array( "slug" => "tours", "with_front" => true ),
                    "query_var" => true,
                    "menu_position" => 23,"menu_icon" => "dashicons-location-alt",      
                    "supports" => array( "title", "comments", "revisions", "thumbnail" ),       
                    "taxonomies" => array( "holiday-type" ),        
                );
                register_post_type( "tours", $args );
             
            // End of cptui_register_my_cpts()
            }
             
             
            add_action( 'init', 'cptui_register_my_taxes' );
            function cptui_register_my_taxes() {
                $labels = array(
                    "name" => __( 'Holiday Types', '' ),
                    "singular_name" => __( 'Holiday Type', '' ),
                    "menu_name" => __( 'Holiday Types', '' ),
                    "all_items" => __( 'All Holiday Types', '' ),
                    "edit_item" => __( 'Edit Holiday Type', '' ),
                    "view_item" => __( 'View Holiday Type', '' ),
                    "update_item" => __( 'Update Holiday Type', '' ),
                    "add_new_item" => __( 'Add New Holiday Type', '' ),
                    "new_item_name" => __( 'New Holiday Type', '' ),
                    "parent_item" => __( 'Parent Holiday Type', '' ),
                    "parent_item_colon" => __( 'Parent Holiday Type:', '' ),
                    "search_items" => __( 'Search Holiday Type', '' ),
                    "popular_items" => __( 'Popular Holiday Types', '' ),
                    "add_or_remove_items" => __( 'Add or Remove Holiday Types', '' ),
                    );
             
                $args = array(
                    "label" => __( 'Holiday Types', '' ),
                    "labels" => $labels,
                    "public" => true,
                    "hierarchical" => true,
                    "label" => "Holiday Types",
                    "show_ui" => true,
                    "query_var" => true,
                    "rewrite" => array( 'slug' => 'holiday-type', 'with_front' => true  'hierarchical' => true ),
                    "show_admin_column" => false,
                    "show_in_rest" => false,
                    "rest_base" => "",
                    "show_in_quick_edit" => false,
                );
                register_taxonomy( "holiday-type", array( "excursion", "hotel", "offer" ), $args );
             
            // End cptui_register_my_taxes()
            }
            add_action( 'init', 'cptui_register_my_cpts' );
            function cptui_register_my_cpts() {
            	$labels = array(
            		"name" => __( 'Excursions', '' ),
            		"singular_name" => __( 'Excursion', '' ),
            		"menu_name" => __( 'Excursions', '' ),
            		"all_items" => __( 'All Excursions', '' ),
            		"add_new" => __( 'Add Excursion', '' ),
            		"add_new_item" => __( 'Add New Excursion', '' ),
            		"edit" => __( 'Edit', '' ),
            		"edit_item" => __( 'Edit Excursion', '' ),
            		"new_item" => __( 'New Excursion', '' ),
            		"view" => __( 'View', '' ),
            		"view_item" => __( 'View Excursion', '' ),
            		"search_items" => __( 'Search Excursions', '' ),
            		);
            
            	$args = array(
            		"label" => __( 'Excursions', '' ),
            		"labels" => $labels,
            		"description" => "Hotels also reference \'Hotels\'",
            		"public" => true,
            		"show_ui" => true,
            		"show_in_rest" => false,
            		"rest_base" => "",
            		"has_archive" => false,
            		"show_in_menu" => true,
            		"exclude_from_search" => false,
            		"capability_type" => "post",
            		"map_meta_cap" => true,
            		"hierarchical" => false,
            		"rewrite" => array( "slug" => "excursion", "with_front" => true ),
            		"query_var" => true,
            		"menu_position" => 20,"menu_icon" => "dashicons-tickets-alt",		
            		"supports" => array( "title", "comments", "revisions", "thumbnail", "page-attributes" ),		
            		"taxonomies" => array( "holiday-type" ),		
            	);
            	register_post_type( "excursion", $args );
            
            	$labels = array(
            		"name" => __( 'Hotels', '' ),
            		"singular_name" => __( 'Hotel', '' ),
            		"menu_name" => __( 'Hotels', '' ),
            		"all_items" => __( 'All Hotels', '' ),
            		"add_new" => __( 'Add Hotel', '' ),
            		"add_new_item" => __( 'Add New Hotel', '' ),
            		"edit" => __( 'Edit', '' ),
            		"edit_item" => __( 'Edit Hotel', '' ),
            		"new_item" => __( 'New Hotel', '' ),
            		"view" => __( 'View', '' ),
            		"view_item" => __( 'View Hotel', '' ),
            		"search_items" => __( 'Search Hotels', '' ),
            		);
            
            	$args = array(
            		"label" => __( 'Hotels', '' ),
            		"labels" => $labels,
            		"description" => "Hotels also reference \'Excursions\'.",
            		"public" => true,
            		"show_ui" => true,
            		"show_in_rest" => false,
            		"rest_base" => "",
            		"has_archive" => false,
            		"show_in_menu" => true,
            		"exclude_from_search" => false,
            		"capability_type" => "post",
            		"map_meta_cap" => true,
            		"hierarchical" => false,
            		"rewrite" => array( "slug" => "hotel", "with_front" => true ),
            		"query_var" => true,
            		"menu_position" => 21,"menu_icon" => "dashicons-store",		
            		"supports" => array( "title", "comments", "revisions", "thumbnail", "page-attributes" ),		
            		"taxonomies" => array( "holiday-type" ),		
            	);
            	register_post_type( "hotel", $args );
            
            	$labels = array(
            		"name" => __( 'Offers', '' ),
            		"singular_name" => __( 'Offer', '' ),
            		"menu_name" => __( 'Offers', '' ),
            		"all_items" => __( 'All Offers', '' ),
            		"add_new" => __( 'Add Offer', '' ),
            		"add_new_item" => __( 'Add New Offer', '' ),
            		"edit" => __( 'Edit', '' ),
            		"edit_item" => __( 'Edit Offer', '' ),
            		"new_item" => __( 'New Offer', '' ),
            		"view" => __( 'View', '' ),
            		"view_item" => __( 'View Offer', '' ),
            		"search_items" => __( 'Search Offers', '' ),
            		);
            
            	$args = array(
            		"label" => __( 'Offers', '' ),
            		"labels" => $labels,
            		"description" => "An \'Offer\' can be made up of Hotels & Excursions",
            		"public" => true,
            		"show_ui" => true,
            		"show_in_rest" => false,
            		"rest_base" => "",
            		"has_archive" => false,
            		"show_in_menu" => true,
            		"exclude_from_search" => false,
            		"capability_type" => "post",
            		"map_meta_cap" => true,
            		"hierarchical" => false,
            		"rewrite" => array( "slug" => "offer", "with_front" => true ),
            		"query_var" => true,
            		"menu_position" => 22,"menu_icon" => "dashicons-smiley",		
            		"supports" => array( "title", "comments", "revisions", "thumbnail", "page-attributes" ),		
            		"taxonomies" => array( "holiday-type" ),		
            	);
            	register_post_type( "offer", $args );
            
            	$labels = array(
            		"name" => __( 'Banners', '' ),
            		"singular_name" => __( 'Banner', '' ),
            		"menu_name" => __( 'Banners', '' ),
            		"all_items" => __( 'All Banners', '' ),
            		"add_new" => __( 'Add Banner', '' ),
            		"add_new_item" => __( 'Add New Banner', '' ),
            		"edit" => __( 'Edit', '' ),
            		"edit_item" => __( 'Edit Banner', '' ),
            		"new_item" => __( 'New Banner', '' ),
            		"view" => __( 'View', '' ),
            		"view_item" => __( 'View Banner', '' ),
            		"search_items" => __( 'Search Banner', '' ),
            		);
            
            	$args = array(
            		"label" => __( 'Banners', '' ),
            		"labels" => $labels,
            		"description" => "Banners shown in various locations across the website",
            		"public" => true,
            		"show_ui" => true,
            		"show_in_rest" => false,
            		"rest_base" => "",
            		"has_archive" => false,
            		"show_in_menu" => true,
            		"exclude_from_search" => false,
            		"capability_type" => "post",
            		"map_meta_cap" => true,
            		"hierarchical" => false,
            		"rewrite" => array( "slug" => "banner", "with_front" => true ),
            		"query_var" => true,
            		"menu_icon" => "dashicons-welcome-widgets-menus",		
            		"supports" => array( "title" ),		
            		"taxonomies" => array( "banner-locations" ),		
            	);
            	register_post_type( "banner", $args );
            
            	$labels = array(
            		"name" => __( 'Tours', '' ),
            		"singular_name" => __( 'Tour', '' ),
            		"menu_name" => __( 'Tours', '' ),
            		"all_items" => __( 'All Tours', '' ),
            		"add_new" => __( 'Add New', '' ),
            		"add_new_item" => __( 'Add New Tour', '' ),
            		"edit" => __( 'Edit', '' ),
            		"edit_item" => __( 'Edit Tour', '' ),
            		"new_item" => __( 'New Tour', '' ),
            		"view" => __( 'View', '' ),
            		"view_item" => __( 'View Tour', '' ),
            		"search_items" => __( 'Search Tours', '' ),
            		);
            
            	$args = array(
            		"label" => __( 'Tours', '' ),
            		"labels" => $labels,
            		"description" => "",
            		"public" => true,
            		"show_ui" => true,
            		"show_in_rest" => false,
            		"rest_base" => "",
            		"has_archive" => false,
            		"show_in_menu" => true,
            		"exclude_from_search" => false,
            		"capability_type" => "post",
            		"map_meta_cap" => true,
            		"hierarchical" => true,
            		"rewrite" => array( "slug" => "tours", "with_front" => true ),
            		"query_var" => true,
            		"menu_position" => 23,"menu_icon" => "dashicons-location-alt",		
            		"supports" => array( "title", "comments", "revisions", "thumbnail" ),		
            		"taxonomies" => array( "holiday-type" ),		
            	);
            	register_post_type( "tours", $args );
            
            // End of cptui_register_my_cpts()
            }
            
            
            add_action( 'init', 'cptui_register_my_taxes' );
            function cptui_register_my_taxes() {
            	$labels = array(
            		"name" => __( 'Holiday Types', '' ),
            		"singular_name" => __( 'Holiday Type', '' ),
            		"menu_name" => __( 'Holiday Types', '' ),
            		"all_items" => __( 'All Holiday Types', '' ),
            		"edit_item" => __( 'Edit Holiday Type', '' ),
            		"view_item" => __( 'View Holiday Type', '' ),
            		"update_item" => __( 'Update Holiday Type', '' ),
            		"add_new_item" => __( 'Add New Holiday Type', '' ),
            		"new_item_name" => __( 'New Holiday Type', '' ),
            		"parent_item" => __( 'Parent Holiday Type', '' ),
            		"parent_item_colon" => __( 'Parent Holiday Type:', '' ),
            		"search_items" => __( 'Search Holiday Type', '' ),
            		"popular_items" => __( 'Popular Holiday Types', '' ),
            		"add_or_remove_items" => __( 'Add or Remove Holiday Types', '' ),
            		);
            
            	$args = array(
            		"label" => __( 'Holiday Types', '' ),
            		"labels" => $labels,
            		"public" => true,
            		"hierarchical" => true,
            		"label" => "Holiday Types",
            		"show_ui" => true,
            		"query_var" => true,
            		"rewrite" => array( 'slug' => 'holiday-type', 'with_front' => true  'hierarchical' => true ),
            		"show_admin_column" => false,
            		"show_in_rest" => false,
            		"rest_base" => "",
            		"show_in_quick_edit" => false,
            	);
            	register_taxonomy( "holiday-type", array( "excursion", "hotel", "offer" ), $args );
            
            // End cptui_register_my_taxes()
            }
          2. Ash Bryant

            I’ve tried adding

            echo '$post_type: <pre>' . $post_type . '</pre>';

            but it doesn’t show anything, but if I change your code to match Colir’s version here …

            1
            2
            3
            4
            5
            6
            7
            
            // Retrieve post type based on post name
                $post_type = $wpdb->get_var(
                    $wpdb->prepare(
                        'SELECT post_type FROM ' . $wpdb->posts . ' WHERE post_name = %s LIMIT 1',
                        $post_name
                    )
                );
            // Retrieve post type based on post name
                $post_type = $wpdb->get_var(
                    $wpdb->prepare(
                        'SELECT post_type FROM ' . $wpdb->posts . ' WHERE post_name = %s LIMIT 1',
                        $post_name
                    )
                );

            it returns as banner, so is it the query here that is the issue?

  27. Ryan Sechrest Post author

    Hi Ash,

    I took your code, with a minor tweak in labels:

    "rewrite" => array( 'slug' => 'holiday-type', 'with_front' => true 'hierarchical' => true ),

    You’re missing a comma after the true before 'hierarchical'.

    Then I took all of my code above, with the revised version from 12/23/14, which basically is this:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    
    function custom_pre_get_posts($query) {
        global $wpdb;
     
        if(!$query->is_main_query()) {
            return;
        }
     
        $post_name = $query->get('pagename');
     
        $result = $wpdb->get_row(
            $wpdb->prepare(
                'SELECT wpp1.post_type, wpp2.post_name AS parent_post_name FROM ' . $wpdb->posts . ' as wpp1 LEFT JOIN ' . $wpdb->posts . ' as wpp2 ON wpp1.post_parent = wpp2.ID WHERE wpp1.post_name = %s LIMIT 1',
                $post_name
            )
        );
     
        switch($result->post_type) {
            case 'tours':
                if ($result->parent_post_name !== '') {
                    $post_name = $result->parent_post_name . '/' . $post_name;
                }
                $query->set('services', $post_name);
                $query->set('post_type', $result->post_type);
                $query->is_single = true;
                $query->is_page = false;
                break;
        }
    }
    function custom_pre_get_posts($query) {
        global $wpdb;
    
        if(!$query->is_main_query()) {
            return;
        }
    
        $post_name = $query->get('pagename');
    
        $result = $wpdb->get_row(
            $wpdb->prepare(
                'SELECT wpp1.post_type, wpp2.post_name AS parent_post_name FROM ' . $wpdb->posts . ' as wpp1 LEFT JOIN ' . $wpdb->posts . ' as wpp2 ON wpp1.post_parent = wpp2.ID WHERE wpp1.post_name = %s LIMIT 1',
                $post_name
            )
        );
    
        switch($result->post_type) {
            case 'tours':
                if ($result->parent_post_name !== '') {
                    $post_name = $result->parent_post_name . '/' . $post_name;
                }
                $query->set('services', $post_name);
                $query->set('post_type', $result->post_type);
                $query->is_single = true;
                $query->is_page = false;
                break;
        }
    }

    I pasted it into a functions.php file on a multisite I’m running, and added multiple tours to two different sites. Each permalink had the post type removed and I saw each tour page render (using the default template).

    There must be something else you have tweaked or installed that is interfering with the code above, but based on what you posted, I can confirm that it works.

    Reply
      1. Ryan Sechrest Post author

        Is that a plugin or are you doing it manually? The site network I tested it on actually uses a top-level domains for each site (as apposed to subdomain or subdirectory), so that does work as well.

        Reply
          1. Ryan Sechrest Post author

            I could definitely see WPML causing issues, since it manipulates database queries. I run a network of sites with WPML, but I don’t remove post type slugs on any of those sites. You might deactivate both the domain mapping and WPML plugin to see if that resolves the issue. If so, then at least you know where to look to find a workaround.

  28. Alex

    Hi, Ryan.
    Thank for you post. It’s very useful.
    But I was faced with another problem. I want to change woocommerce product url. Page returns a 404 error, and in WP_Query Object object i have

    [query] => Array
    (
        [error] => 404
    )

    No relevant information. What it can be? It looks like the function is executed after construction of the post.
    I would be grateful for any advice

    Reply
    1. Ryan Sechrest Post author

      Hi Alex! I don’t use WooCommerce, so I don’t have any information that would by helpful here. I will say that my tutorial is for changing the URL for post types that you register. Changing the URLs in post types registered by a third-party plugin might have unintended consequences.

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *