Pages

Friday, January 4, 2013

Remove slug from custom post type - [resolved]

Add custom post type

In this example I’ll add “books” as a custom post type. What we want to achieve is that the urls are http://siteurl/%bookname%/

First we need to have a closer look at what rewrite options we have when we register a new post type with register_post_type.

For my hack to work you need to add a slug and set with_front to false:

Step 1: Register post type

First we will start with registering our new post type

add_action('init', 'demo_register_post_type');
    
    function demo_register_post_type() {
        register_post_type('products', array(
            'labels' => array(
            'name' => 'Products',
            'singular_name' => 'Product',
            'add_new' => 'Add new product',
            'edit_item' => 'Edit product',
            'new_item' => 'New product',
            'view_item' => 'View product',
            'search_items' => 'Search products',
            'not_found' => 'No products found',
            'not_found_in_trash' => 'No products found in Trash'),
            'public' => true,
            'rewrite' => array("slug" => "", "with_front" => true),
            'supports' => array('title','editor', 'thumbnail' )
        ));
    }

If you now add a book it will get the url http://siteurl/products/%post_title%/, so far so good.

Step 2: Add rewrite rule

We need to add a new rewrite rule to make the system recognise books without the slug /book/.
It’s important that you hook the rewrite rule after the theme setup is finished, otherwise it will be overwritten.
in this case, the regular expression to look for anything in the root will be “(.*?)$”, basically look for anything.
Our redirection is the query ‘index.php?products=$id’.

function products_rewrite_rule() {
    add_rewrite_rule('(.*?)$', 'index.php?products=$matches[1]', 'top');
}
add_action('after_theme_setup', 'products_rewrite_rule');

Step 3: .htaccess

Add a rule to redirect /products/%post_title%/ to /%post_title%/ in .htaccess
 
RewriteRule ^products/(.+)$ /$1 [R=301,L]

Step 4: Fix the permalink that is shown when editing

When adding a new book in this case or editing an old one, the permalink will still show “Permalink: http://siteurl/products/%post_title%/” and View will also go to the url with the slug. Here is the final piece to hack the slug away

function remove_slug($permalink, $post, $leavename) {
 $permalink = str_replace(get_bloginfo('url') . '/products' , get_bloginfo('url'), $permalink);
 return $permalink;
}
add_filter('post_type_link', 'remove_slug', 10, 3);

No comments: