I was wondering how i can remove the prefix from the slugs of custom post types using htaccess rules or any other appropriate method.

Currently my custom post types look like this:

http://www.domain.com/os_estate/5-bedroom-property-for-sale

and i would simply like this to be:

http://www.domain.com/5-bedroom-property-for-sale

I was able to achieve this via a plugin but it significantly added to the page load time..

My common settings in Permalinks is set to “Post Name”

3 Answers
3

There is a simpler and lighter solution:

First: set the slug argument for your custom post type to “https://wordpress.stackexchange.com/” when registering the post type:

add_action( 'init', 'register_my_post_type' );
function register_my_post_type() {
    $args = array(
            //The rest of arguments you are currently using goes here
            'rewrite'    => array(
                             'slug' => "https://wordpress.stackexchange.com/"
                             )
     );
     register_post_type( 'my-post-type', $args );   
}

Second: in preg_get_posts() action hook include your post type in the query when only the $query->query['name'] is present:

add_action( 'pre_get_posts', 'wpse_include_my_post_type_in_query' );
function wpse_include_my_post_type_in_query( $query ) {

     // Only noop the main query
     if ( ! $query->is_main_query() )
         return;

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

      // Include my post type in the query
     if ( ! empty( $query->query['name'] ) )
          $query->set( 'post_type', array( 'post', 'page', 'my-post-type' ) );
 }

Third: I’ve found that in some situations there are conflicts with pages and single posts. I’ve been able to avoid this conflict by checking if a page with the request name exists and overriding the query conditionals but I’m not sure if more conflict can happens:

add_action( 'parse_query', 'wpse_parse_query' );
function wpse_parse_query( $wp_query ) {

    if( get_page_by_path($wp_query->query_vars['name']) ) {
        $wp_query->is_single = false;
        $wp_query->is_page = true;
    }

}

IMPORTANT: You need to flush the rewrite rules. You can do it by viviting the permalink options page in the admin area. This is needed because we are registering a new rewrite rule, so the current rewrite rules stored in the database must be regenerated.

Tags:

Leave a Reply

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