<?php
// remove cpt slug from permalinks
function remove_cpt_slug( $post_link, $post, $leavename ) {
if ( $post->post_type != 'products' ) {
return $post_link;
} else {
$post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );
return $post_link;
}
}
add_filter( 'post_type_link', 'remove_cpt_slug', 10, 3 );
//Remvove slug
function parse_request_remove_cpt_slug( $query ) {
if ( ! $query->is_main_query() || 2 != count( $query->query ) || ! isset( $query->query['page'] ) ) {
return;
}
if ( ! empty( $query->query['name'] ) ) {
global $wpdb;
$cpt = $wpdb->get_var("SELECT post_type FROM $wpdb->posts WHERE post_name = '{$query->query['name']}'");
// Add CPT to the list of post types WP will include when it queries based on the post name.
$query->set( 'post_type', $cpt );
}
}
add_action( 'pre_get_posts', 'parse_request_remove_cpt_slug' );
//Add rewrite rule
function rewrite_rule_remove_cpt_slug() {
add_rewrite_rule(
'(.?.+?)(?:/([0-9]+))?/?$',
'index.php?custom_post_type=$matches[1]/$matches[2]&post_type=custom_post_type',
'bottom'
);
}
add_action( 'init', 'rewrite_rule_remove_cpt_slug', 1, 1 );