2
votes

My initial goal is to be able to display Woocommerce Products in the sidebar, sorted by Title. Currently the only sorting options in this widget are Date, Price, Random and Sales.

I was able to add the Title sorting option in 2 parts in class-wc-widget-products.php:

'orderby' => array(
                'type'  => 'select',
                'std'   => 'date',
                'label' => __( 'Order by', 'woocommerce' ),
                'options' => array(
                    'title'   => __( 'Title', 'woocommerce' ),
                    'date'   => __( 'Date', 'woocommerce' ),
                    'price'  => __( 'Price', 'woocommerce' ),
                    'rand'   => __( 'Random', 'woocommerce' ),
                    'sales'  => __( 'Sales', 'woocommerce' ),
                ),

And here:

switch ( $orderby ) {
    case 'title' :
        $query_args['orderby']  = 'title';
        break;
    case 'price' :
        $query_args['meta_key'] = '_price';
        $query_args['orderby']  = 'meta_value_num';
        break;
    case 'rand' :
        $query_args['orderby']  = 'rand';
        break;
    case 'sales' :
        $query_args['meta_key'] = 'total_sales';
        $query_args['orderby']  = 'meta_value_num';
        break;
    default :
        $query_args['orderby']  = 'date';
}

This customization works fine, but:

My question: where should I save this customized "class-wc-widget-products.php" file preventing it from being overwritten at the next Woocommerce update?
OR... is there a more elegant way to accomplish this? Thank You!

1

1 Answers

0
votes

Kindly, making what you have done is something really to avoid.
It's prohibited for developers
(so I had to rename the title of your question).

First inconvenient (as you already know): you loose your changes when plugin is updated.

Nobody override core files… So please remove all your changes or get the original file back.

That is why actions and filters exist all through the code

The correct way to force orderby by "title" can be done this way:

add_filter( 'woocommerce_products_widget_query_args','title_orderby_products_widget_query_arg', 10, 1 );
function title_orderby_products_widget_query_arg( $query_args ) {
    // set 'title' for orderby 
    $query_args['orderby'] = 'title';

    return $query_args;
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

This should work for you.

Then you can add some conditions to better target this...


Official documentation: WooCommerce Action and Filter Hook Reference