fbpx
How to Remove the Product-Category Slug in WordPress WooCommerce

How to Remove the Product-Category Slug in WordPress WooCommerce

This WordPress WooCommerce fix will allow you to remove the product-category slug from the URL in WordPress WooCommerce without using a plugin.

Example:
From: https://mywebshop.com/shop/product-category/apparel/black-pants
To: https://mywebshop.com/shop/apparel/black-pants

Remove the product-category slug from the WordPress WooCommerce URL

1. Add this snippet to the functions.php file in your WordPress theme.

add_filter('request', function( $vars ) {
   global $wpdb;
   if( ! empty( $vars['pagename'] ) || ! empty( $vars['category_name'] ) || ! empty( $vars['name'] ) || ! empty( $vars['attachment'] ) ) {
      $slug = ! empty( $vars['pagename'] ) ? $vars['pagename'] : ( ! empty( $vars['name'] ) ? $vars['name'] : ( !empty( $vars['category_name'] ) ? $vars['category_name'] : $vars['attachment'] ) );
      $exists = $wpdb->get_var( $wpdb->prepare( "SELECT t.term_id FROM $wpdb->terms t LEFT JOIN $wpdb->term_taxonomy tt ON tt.term_id = t.term_id WHERE tt.taxonomy = 'product_cat' AND t.slug = %s" ,array( $slug )));
      if( $exists ){
         $old_vars = $vars;
         $vars = array('product_cat' => $slug );
         if ( !empty( $old_vars['paged'] ) || !empty( $old_vars['page'] ) )
            $vars['paged'] = ! empty( $old_vars['paged'] ) ? $old_vars['paged'] : $old_vars['page'];
         if ( !empty( $old_vars['orderby'] ) )
            $vars['orderby'] = $old_vars['orderby'];
         if ( !empty( $old_vars['order'] ) )
            $vars['order'] = $old_vars['order']; 
      }
   }
   return $vars;
});

2. Enter a “.” in the “product category base” field on the permalinks settings page (wp-admin/options-permalink.php).

How to Remove the Product-Category Slug in WordPress WooCommerce

Enter a “.”in the “product category base” field.

WordPress Hosting

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

WordPress Snippet Info

Tested with Wordpress v. 5.0

How to Remove the Product-Category Slug in WordPress WooCommerce
5 (100%) 3 vote[s]
Please report broken snippets.
Report Broken Snippet

Recent Comments