Puddinq.com sharing knowledge

WordPress CPT drop permalink prefix

WordPress CPT drop permalink prefix

When you create a custom post type, the url is prefixed with the post type name or slug, you can remove that on the output:

function remove_slug($post_link, $post, $leavename)
{

    if ('YOUR_CPT_TYPE' != $post->post_type || 'publish' != $post->post_status) {
        return $post_link;
    }

    $post_link = str_replace('/'.$post->post_type.'/', '/', $post_link);

    return $post_link;
}

add_filter('post_type_link', 'remove_slug', 10, 3);

To understand the requests made without this prefix you need to tell WordPress your request can be made without a prefix, just as pages and posts

function understand_request(\WP_Query $query)
{
    if (!$query->is_main_query() || 2 != count($query->query) || !isset($query->query['page'])) {
        return $query;
    }
    if (empty($query->query['name']) === false && $query->query['name'] != '404') {
        $query->set('post_type', ['post', 'YOUR_CPT_TYPE', 'page']);
    }

    return $query;
}

add_action('pre_get_posts', 'understand_request');