0

Im trying to remove slug from my Custom Post Types. I've added

'rewrite' => array(
    'slug' => '/'
)

and based on this post https://wordpress.stackexchange.com/a/144356/116847 I've added:

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', 'physio_methods', 'treatment' ) );
 }

 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;
    }

}

otherwise, posts was mixed with pages and gets 404. But now, I have problem with posts categories - link to category display post, not the archive page.

I need to fully remove slug from my CPT. Is there any good (no plugin) solution for that?

Thanks!

1 Answer 1

0

This is a two-step process. First, you need to remove the slug from the default URL. (use a unique slug while registering the CPT).

function wpse413969_remove_cpt_slug( $post_link, $post ) {
    if ( $post->post_type == 'YOUR_CPT' && $post->post_status == 'publish') {
        $post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );
    }
    return $post_link;
}
add_filter( 'post_type_link', 'wpse413969_remove_cpt_slug', 10, 2 );

Then include your CPT in main query.

function wpse413969_add_cpt_names_to_main_query( $query ) {
   
    // Return if this is not the main query.
    if ( ! $query->is_main_query() ) {
        return;
    }
    
    // Return if this query doesn't match our very specific rewrite rule.
    if ( ! isset( $query->query['page'] ) || 2 !== count( $query->query ) ) {
        return;
    }
    
    // Return if we're not querying based on the post name.
    if ( empty( $query->query['name'] ) ) {
        return;
    }
    
    // Add CPT to the list of post types WP will include when it queries based on the post name.
    $query->set( 'post_type', array( 'post', 'page', 'YOUR_CPT' ) );
}
add_action( 'pre_get_posts', 'wpse413969_add_cpt_names_to_main_query' );

This, IMHO, is a bad practice. There are some good reasons why WordPress includes the slug in CPTs. To avoid conflict with default post and pages, always use unique slugs for your CPT posts.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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