1

I'm creating a new website based on a theme using custom post type and WordPress 3.2.1.

The problem is that my content was previously using %postname% permalinks and all my SEO is build on this. Using CPT add a slug like : http://mysite.com/slug-cpt/postname

I tried this rule in the register_post_type function but it doesn't work :

'rewrite' => array('slug' => false, 'with_front' => false)

I also read this but it's not good for me : Permalinks in Custom Post types

Any idea ?

2

This is a tricky one, I had exactly the same problem but after a lot of debugging and troubleshooting I managed to fix it.

The trick is to add a new rewrite rule:

function book_rewrite_rule() {
    add_rewrite_rule( '(.*?)$', 'index.php?book=$matches[1]', 'top' );
}
add_action( 'after_theme_setup', 'book_rewrite_rule' );
  • 1
    your sites down :( – Ben Racicot Jun 15 '14 at 21:38
0

Question is quite old, but issues still exist. The best way to remove the slug from URL is writing a few lines of code in your functions.php file.

Another way to do it is passing the rewrite parameters as follows:

'rewrite' => array('slug' => '/', 'with_front' => false)

But this is not recommended as it causes 404 error in other pages. So you should opt for the solution of getting into your theme's functions.php.

/**
 * Remove the slug from published post permalinks. Only affect our CPT 
though.
 */
function sh_remove_cpt_slug( $post_link, $post, $leavename ) {

    if ( in_array( $post->post_type, array( 'cpt' ) )
        || 'publish' == $post->post_status )
        $post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );
        return $post_link;
}
add_filter( 'post_type_link', 'sh_remove_cpt_slug', 10, 3 );

This will remove the slug from the URL for the published post. This will still cause an error since it specifies that only 'post' and 'page' post types can have url without a post-type slug.

Now to teach WP that out CPT will also have URL without slug, we need to get this in our functions.php

function sh_parse_request_tricksy( $query ) {

    // Only loop the main query
    if ( ! $query->is_main_query() ) {
        return;
    }

    // Only loop our very specific rewrite rule match
    if ( 2 != count( $query->query )
        || ! isset( $query->query['page'] ) )
        return;

    // 'name' will be set if post permalinks are just post_name, otherwise the page rule will match
    if ( ! empty( $query->query['name'] ) ) {
        $query->set( 'post_type', array( 'cpt' ) );
    }
}
add_action( 'pre_get_posts', 'sh_parse_request_tricksy' );

Ref: https://wordpress.stackexchange.com/a/320711/98322

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.