Accessing WooCommerce product categories before initialising widget areas

I intend to programmatically create a widget area for each product category within WooCommerce.

I currently have the following code in my functions.php:

$args = array(
‘taxonomy’ => ‘product_cat’,
‘hide_empty’ => false,
‘parent’ => 0,
);
$product_cats = get_terms( $args );
foreach ( $product_cats as $product_cat ) {
register_sidebar(
array(
‘name’ => ‘Filter sidebar -‘ . $product_cat->name,
‘id’ => ‘filter_sidebar_’ . $product_cat->name,
‘before_widget’ => ‘<div class=”filter-sidebar-‘ . $product_cat->name . ‘”>’,
‘after_widget’ => ‘</div>’,
‘before_title’ => ‘<h2 class=”filter-title”>’,
‘after_title’ => ‘</h2>’,
)
);
}

My problem is that this returns an error: Notice: Trying to get property of non-object in …/functions.php on line xyz, presumably because the action for registering widget areas fires before WooCommerce has initialised its product categories.

How do I access the product categories in order to make this loop work?

Read more here:: Accessing WooCommerce product categories before initialising widget areas

Leave a Reply

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