NB: Make sure you do a back up of your theme, files and database before attempting the tutorials

Intermediate

---- Last modified : Sep 11 2022

Estimated reading time : 1 minute, 41 seconds - 120 words

With this tutorial, we will show you a way to display your WooCommerce product categories outside of widgets. We will run a query that will display the categories matching the WooCommerce taxonomy.

To find your WordPress taxonomy, simply access your category’s Post Type and look at the URL.
In this example, we see this: taxonomy=product_cat in the URL so the taxonomy’s name is WooCommerce.

Display WooCommerce Product Categories

<?php 
$categories = get_categories('taxonomy=product_cat&amp;hide_empty=1');
$select = "<select name='cat' id='cat' class='postform'>
<option value='".$category->slug."'>Quelle Occasion ?</option>";
  foreach($categories as $category){
  if($category-&gt;count &gt; 0){
      $select.= "<option value='".$category->slug."'>".$category->name."</option>";
  }}
$select.= "</select>";
echo $select;
?>

With the Javascript, we will specify the desired category and redirect it to the URL matching your category.

After our query, we will add our JavaScript.

<script type="text/javascript">
var dropdown = document.getElementById("cat");
function onCatChange() {
if ( dropdown.options[dropdown.selectedIndex].value != -1 ) {
location.href = "<?php echo home_url();?>/boutique/categorie/"+dropdown.options[dropdown.selectedIndex].value+"/";
}}
dropdown.onchange = onCatChange;
</script>

When we look at the redirected ULR in the previous code.
Simply update the URL with the slug category.

location.href = "<?php echo home_url();?>/boutique/categorie/"+dropdown.options[dropdown.selectedIndex].value+"/";

Leave a Reply

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

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>