Thread Starter
soders
(@soders)
I solved it with the kind help of Chatgpt! 🙂
Ill be happy to share the snippet if someone wants it. 🙂
-
This reply was modified 37 minutes ago by
soders.
Be careful with ChatCPT codes, they are sometimes incorrect. You are welcome to share the snippet. And also set the topic to done when it is finished for you.
Thread Starter
soders
(@soders)
Yes, I know, but it worked out of the box so to speak! 🙂
Here is the snippet, I have added it to my-custom-code.php
// Modified category widget
// Function to define and register the custom widget
function initialize_custom_wc_widget() {
// Define the custom widget class
class Custom_WC_Product_Categories_Widget extends WP_Widget {public function __construct()
parent::__construct(
'custom_wc_product_categories',
'Custom WC Product Categories',
array('description' => 'Displays product categories with custom functionality.')
);
public function widget($args, $instance)
// Start widget output
echo $args['before_widget'];
// Display widget title
if (!empty($instance['title']))
echo $args['before_title'] . $instance['title'] . $args['after_title'];
// List all main categories
$main_category_args = array(
'taxonomy' => 'product_cat',
'hide_empty' => 1,
'parent' => 0
);
$main_categories = get_categories($main_category_args);
foreach ($main_categories as $cat)
echo '<a href="' . get_term_link($cat->term_id) . '">' . $cat->name . '</a><br>';
// Get the current category
$current_cat = get_queried_object();
// If we are on a category page and it's the current main category or one of its subcategories, list subcategories
if (isset($current_cat->term_id) && $current_cat->taxonomy == 'product_cat')
if ($current_cat->term_id == $cat->term_id
// End widget output
echo $args['after_widget'];
// Recursive function to list subcategories
private function list_sub_categories($parent_id, $current_cat, $level = 1)
$sub_category_args = array(
'taxonomy' => 'product_cat',
'hide_empty' => 1,
'parent' => $parent_id
);
$sub_categories = get_categories($sub_category_args);
foreach ($sub_categories as $sub_cat) $current_cat->parent == $sub_cat->term_id)
$this->list_sub_categories($sub_cat->term_id, $current_cat, $level + 1);
public function form($instance)
// Add form fields for widget settings if needed
public function update($new_instance, $old_instance)
// Add update logic for widget settings if needed
return $new_instance;
}
// Register the custom widget
register_widget('Custom_WC_Product_Categories_Widget');}
// Add an action to run our function when widgets are initialized
add_action('widgets_init', 'initialize_custom_wc_widget');