MENU

Get WooCommerce Parent Categories

July 25, 2021
Posted in: ,

Oxygen's Categories List element isn't currently able to display WooCommerce parent categories only. However, there is a simple workaround using Oxygen's Code Block element. To use the workaround, add a Code Block to your design and set the width of the Code Block to 100% via Advanced > Size & Spacing.

Next, add the following PHP to the Code Block:

<?php
$terms = get_terms(['taxonomy' => 'product_cat', 'hide_empty' => false, 'parent' => 0]);

if ($terms)
{ ?>

<div class="oxy-woo-product-categories oxy-woo-element">
   <div class="woocommerce columns-4">
      <ul class="products columns-4">
  
  <?php
    foreach ($terms as $term)
    {
        // GET IMAGE
        // get the thumbnail id
        $thumbnail_id = get_woocommerce_term_meta($term->term_id, 'thumbnail_id', true);

        // get the image URL
        $image = wp_get_attachment_url($thumbnail_id);
        $srcset = wp_get_attachment_image_srcset($thumbnail_id, array(
            300,
            300
        ));

        if (empty($image))
        {
            $image = '/wp-content/uploads/woocommerce-placeholder-300x300.png';
        }

        // GET NAME
        $cat_name = $term->name;

        // GET URL
        $cat_url = get_term_link($term->term_id, 'product_cat');

?>

         <li class="product-category product first">
            <a href="<?php echo $cat_url; ?>">
               <img src="<?php echo $image; ?>" srcset="<?php echo esc_attr($srcset); ?>" alt="<?php echo $cat_name; ?>" width="300" height="300">		
               <h2 class="woocommerce-loop-category__title">
                  <?php echo $cat_name; ?>	
               </h2>
            </a>
         </li>

<?php
    }

?>
  
      </ul>
   </div>
</div>

<?php
}

?>

That should be all you need to do to see your parent categories! If you wish to hide empty categories, then you can set "hide_empty" to "true" on the second line.

Tutorial written by Soph Simmonds
Director & Web Developer at WinuSoft Web Design & Senior Support Specialist at Oxygen. When she's not working, Soph can usually be found mountain biking with her partner, Luis.

Get in Touch

Contact us about any web, design or branding project that you have in mind. We're sure that you'll find our approach and dedication will be just what you need.

We’re always happy to discuss your project with you. Just fill out the form or give us a call to get started.
info@winusoft.co.uk
07889 216767
winusoft.co.uk
facebook-squarelinkedin-squaregithub-squaretwitterfacebookenvelopelinkedinxinginstagrampaper-planepinterest-pwhatsappcommentinghomemagic-wandcloud-uploaddatabaseenvelopeeyefile-addgraduation-hatpicturebooksmartphonemenuchevron-down