function remove_cpt_slug($post_link, $post) {
// Get all custom post types
$args = array(
'public' => true,
'_builtin' => false // This excludes default post types
);
$post_types = array_keys(get_post_types($args, 'names'));
if (!in_array($post->post_type, $post_types) || 'publish' !== $post->post_status) {
return $post_link;
}
//post_type_link 钩子是过滤文章单页的链接
return str_replace('/' . $post->post_type . '/', '/', $post_link);
}
add_filter('post_type_link', 'remove_cpt_slug', 10, 2);
function parse_request_for_cpt($query) {
if (!$query->is_main_query() || is_admin()) {
return;
}
if (!isset($query->query['name'])) {
return;
}
$path = trim($query->query['name'], '/');
// Get all custom post types
$args = array(
'public' => true,
'_builtin' => false
);
$post_types = array_keys(get_post_types($args, 'names'));
// Check each custom post type for matching post
foreach ($post_types as $post_type) {
$custom_post = get_page_by_path($path, OBJECT, $post_type);
if ($custom_post) {
$query->set('post_type', array($post_type));
$query->set('name', $path);
break;
}
}
}
add_action('pre_get_posts', 'parse_request_for_cpt');