Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove taxonomy slug from custom post type url?

Tags:

I have a custom post type(product) with taxonomy product-type. One of my url like this:
http://www.naturesbioscience.com/product-type/immune-support-supplements/
I want this like:
http://www.naturesbioscience.com/immune-support-supplements/

I have used "rewrite" => array('slug' => '/ ', 'with_front' => false in register_taxonomy function and I got the url like:
http://www.naturesbioscience.com/immune-support-supplements/
But I got 404 not found in other pages.

Anyone can help me?

like image 857
DevzValley Avatar asked Dec 19 '16 20:12

DevzValley


1 Answers

I think you forgot to rewrite custom taxonomy post slug.
Write this in your register_post_type methord.

'rewrite' => array('slug' => 'product-type')

Now you have to remove product-type slug from your custom products

/**
 * Remove the slug from published post permalinks.
 */
function custom_remove_cpt_slug($post_link, $post, $leavename)
{
    if ('product-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', 'custom_remove_cpt_slug', 10, 3);

Now as you have removed the custom post type slug so WordPress will try to match it with page or post so you have tell WP to check the URL in you custom post type also. So use this for that:

function custom_parse_request_tricksy($query)
{
    // Only noop the main query
    if (!$query->is_main_query())
        return;

    // Only noop our very specific rewrite rule match
    if (2 != count($query->query) || !isset($query->query['page']))
    {
        return;
    }

    // 'name' will be set if post permalinks are just post_name, otherwise the page rule will match
    if (!empty($query->query['name']))
    {
        $query->set('post_type', array('post', 'product-type', 'page'));
    }
}

add_action('pre_get_posts', 'custom_parse_request_tricksy');

Reference: Remove The Slugs from Custom Post Type URL

Hope this helps!

like image 157
Raunak Gupta Avatar answered Sep 23 '22 16:09

Raunak Gupta