Archived topic
Elements Hooks and WooCommerce
3 replies · Started by Sean on January 26, 2022
I am trying to use Hooks to add banner notices above WooCommerce products that are in certain categories.
I have categories set up like this:
main-cat1
- subcat11
- subcat12
- subcat13
main-cat2
- subcat21
- subcat22
- subcat23
main-cat3
- subcat31
- subcat32
- subcat33
I want to display the banner only in the products in the sub categories of, for example, main-cat1.
I tried to set the Display Location as main-cat1 but it doesn't work as the products are only in the sub categories
I have:
Location: woocommerce_before_main_content
Display: Product Category: subcat11, subcat12, subcat13 etc
This works - but, I have 30+ sub-categories and entering each one into the Display dialogue is very time consuming as I want to do similar things with the other parent categories!
Is there a way of getting it to display in products in sub categories by just having the parent selected?
Thanks!
Hi there,
It would be good to be able to define parent posts/categories in Display Rules.
For now, it's not possible, so we need to use a filter.
For example:
add_filter( 'generate_element_display', function( $display, $element_id ) {
/// Change 123 below to the ID of the Element we're targeting.
if ( 123 === (int) $element_id ) {
$args = array(
'include' => get_the_ID(),
'category' => 123, // Change 123 to the parent category ID we're checking for children in.
'fields' => 'ids',
);
if ( 0 < count( get_posts( $args ) ) ) {
$display = true;
}
}
return $display;
}, 10, 2 );
Let me know if that does the trick or not :)
Thanks for the replay Tom!
I've tried that and it doesn't work - it will only show in products that are assign to the parent and not the child categories.
Cheers
Hi there,
did you modify both the IDs?
This line:
if ( 123 === (int) $element_id ) {
the 123 refers to the ID of the Element.
And the other line is commented for the Category ID.