wordpressCPTCPT UI

How to remove the custom post type name (CPT) from the URL/Slug?

By July 16, 2020 No Comments

My usecase was I was having a link domain.com/tutors/tutor-name. The tutors is cpt and the tutor-name is the slug.

Desired output was domain.com/tutor-name.

The following code is an extract from the StackExchange but it contains a few comments that clarify a few things for me.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/**
 *
 * Source: https://wordpress.stackexchange.com/questions/203951/remove-slug-from-custom-post-type-post-urls
 *
 * Doesn't change the permalink (get_permalink(id)) for the cpt post but the expected link does work with just /slug instead of /tutors(cpt)/slug
 *
 * You can do the following to manipulate the permalink
 *
 * ```
 *
 *   'tutorProfileLink' => str_replace('/tutors/', '/', get_permalink(get_the_ID()))
 *
 * ```
 *
 * Please note the original link of /tutors(cpt)/slug will still be working as is and also /slug will work
 *
 * @param $post_link
 * @param $post
 * @param $leavename
 * @return mixed
 *
 */

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

    if ('events' != $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', 'na_remove_slug', 10, 3);

function na_parse_request($query)
{

    if (!$query->is_main_query() || 2 != count($query->query) || !isset($query->query['page'])) {
        return;
    }

    if (!empty($query->query['name'])) {
        $query->set('post_type', array('post', 'tutors', 'page'));
    }
}

add_action('pre_get_posts', 'na_parse_request');

I also kept the above settings. Not that it did any magic but just for having the log.