Remove the parent slug in a CPT URL

Question

Here is the code that I insert in my functions.php to remove the slug of a CPT present in the URL :

    /**
     * Remove the custom post type slug from URL
     */
    function wpc_remove_cpt_slug($post_link, $post, $leavename) {
        if ('SLUG' != $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', 'wpc_remove_cpt_slug', 0, 3); 
    
    function wpc_parse_request_trick($query) {
        if (! $query->is_main_query())
        return;
    
        if (2 != count($query->query) || ! isset($query->query['page'])) {
            return;
        }
    
        if (! empty( $query->query['name'])) {
            $query->set('post_type', array('post', 'SLUG', 'page'));
        }
    }

add_action('pre_get_posts', 'wpc_parse_request_trick');

I have been using this for several years and it works perfectly for the need in question.

I currently need to create a parent/child relationship with a CPT while keeping short URLs of the form domainname.fr/title-publication/

I use CPT UI to create my CPTs. I have selected “true” in Hierarchy allowing me to have parent-child relationships for the CPT in question.

Let’s take an example with a car brand as a parent and a model as a child.

I obtain the URL for the child CPT: nomdedomaine.fr/tesla/model-3/

But I need this : nomdedomaine.fr/model-3/

Being not at all an experienced developer, I did my research and adapted the following code that I always inserted in functions.php :

/**
 * Remove the parent custom post type slug from URL
 */
function df_custom_post_type_link( $post_link, $id = 0 ) {  
    $post = get_post($id);  
    if ( is_wp_error($post) || 'SLUG' != $post->post_type || empty($post->post_name) )  
        return $post_link;  
    return home_url(user_trailingslashit( "$post->post_name" ));  
}
add_filter( 'post_type_link', 'df_custom_post_type_link' , 10, 2 );

function df_custom_rewrite_rule() {
    add_rewrite_rule('(.*?)$', 'index.php?news=$matches[1]', 'top');
}
add_action('init', 'df_custom_rewrite_rule');

My children’s CPTs have a correct URL with: nomdedomaine.fr/model-3/

But as soon as I make changes in the Back-Office such as adding content or deleting content or creating a new menu, I then have a big incomprehensible bug such as all my URLs start having a redirection to the homepage, I mean nomdedomaine.fr.

I would like to make it clear that this is really all my URLs in their entirety, I mean not just the URLs of the CPT in question.

Has anyone ever succeeded in correctly removing the parent slug in a CPT URL ?

Many thanks in advance

0
PurWeb 2 months 0 Answers 6 views 0

Leave an answer