How to Remove the Product Category Slug in woocommerce WordPress

How To Remove The Product Category Slug In Woocommerce WordPress
How To Remove The Product Category Slug In Woocommerce WordPress

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

Example:
Changing From: https://yourwebaddress.com/shop/product-category/cars/lexus-jeep
To: https://yourwebaddress.com/shop/cars/lexus-jeep

To remove the WordPress WooCommerce product-category slug

1. Add this code to the functions.php file in your WordPress site theme and save.

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. Go to the “product category base” field on the permalinks settings page (wp-admin/options-permalink.php) and add a dot “.”

How To Remove The Product Category Slug In WordPress Woocommerce Preview
How To Remove The Product Category Slug In WordPress Woocommerce Preview

3.Then save to refresh the rewrite rules.

Spread the love

You Might Also Like

Leave a Reply

Your email address will not be published.