How to alter Elementor’s WooCommerce query arguments?

How to alter Elementor’s WooCommerce query arguments?

I had this extra-special query on a WooCommerce widget of Elementor and I’ve noticed that there is no easy way to alter the query. So I’ve created a small class that will help you with this.

The main idea is that I’ve also added a couple of extra controls on the WooCommerce widget itself. But that’s a story for another time. So here is how you can alter the WooCommerce query arguments in an Elementor widget:

class AlterMyWooWidget
{
    protected $widget;
    protected $filterPriority = 99;

    public function __construct()
    {
        add_action('elementor/widget/before_render_content', [$this, '_beforeRender']);
    }

    public function _beforeRender($widget)
    {
        if ($widget->get_name() !== 'woocommerce-products') {
            return;
        }

        if (!$widget->get_settings('my-query-altering-setting')) {
            return;
        }

        $this->widget = $widget;

        add_filter('woocommerce_shortcode_products_query', [$this, '_wooQuery'], $this->filterPriority, 3);
    }

    public function _wooQuery($args, $attrs, $type)
    {
        remove_filter('woocommerce_shortcode_products_query', [$this, '_wooQuery'], $this->filterPriority);

        $args['author__in'] = [10, 22]; // or do something with `$widget->get_settings('my-query-altering-setting')` 

        return $args;
    }
}

new AlterMyWooWidget;

The reason you need to do it this way is that I couldn’t find any other way to pass the widget settings to the woocommerce_shortcode_products_query filter.

That’s about all.

Adaugă un comentariurăspuns pentru

Poți adăuga bucăți de cod folosind [code]codul tău aici[/code], [js][/js], [php][/php] etc.

Link-urile în context sunt binevenite. Comentariile fără nume/email valid sunt șterse.
PS: Comentariul NU este editabil.

Acest sit folosește Akismet pentru a reduce spamul. Află cum sunt procesate datele comentariilor tale.

Site-ul blog.iamntz.com utilizează cookie-uri. Continuarea navigării presupune acceptarea lor. Mai multe informații.

windows apple dropbox facebook twitter