0

I'm trying to extend the woocommerce class used to create the product categories widget in my own plugin which adds a new taxonomy for woo commerce products called "departments".

When I extend WP_Widget everything works just fine and I see a new widget that I can add in Appearance->Widgets. However, when I'm trying to extend WC_Widget or WC_Widget_Product_Categories I simply don't see a new widget, even though I'm not getting any php errors.

Here's what I have which doesn't work:

//get the base classes
if(!class_exists('WC_Widget_Product_Categories')) {
    require_once ABSPATH . 'wp-content/plugins/woocommerce/includes/abstracts/abstract-wc-widget.php';
    require_once ABSPATH . 'wp-content/plugins/woocommerce/includes/widgets/class-wc-widget-product-categories.php';
}

/**
 * Product departments widget class.
 *
 * @extends WC_Widget_Product_Categories
 */
class WC_Widget_Product_Departments extends WC_Widget_Product_Categories {
    /**
     * Constructor.
     */
    public function __construct() {
        $this->widget_cssclass    = 'woocommerce widget_product_departments';
        $this->widget_description = __( 'A list or dropdown of product departments.', 'woocommerce' );
        $this->widget_id          = 'woocommerce_product_departments';
        $this->widget_name        = __( 'Shop Departments', 'woocommerce' );

        parent::__construct();
    }
}

and in my main plugin file:

add_action( 'widgets_init', 'register_department_widgets', 15 );

function register_department_widgets() {
  register_widget( 'WC_Widget_Product_Departments' );
}

However, if I change the class being extended it does work:

class WC_Widget_Product_Departments extends WC_Widget

What am I doing wrong if I want to extend the WC_Widget_Product_Categories class?

1 Answer 1

2

When calling parent::__construct() from WC_Widget_Product_Departments the constructor of WC_Widget_Product_Categories immediately overwrites the class properties (especially the widget_id), see here at GitHub. So you have to extend WC_Widget to create a new widget and then you can copy anything what you need in your widget from WC_Widget_Product_Categories to WC_Widget_Product_Departments.

1
  • Thats a shame, I was trying to stay as DRY as possible...
    – Ralphonz
    Commented Oct 12, 2018 at 14:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.