Woocommerce 小部件产品按标题排序

Woocommerce Widget Product order by title

我最初的目标是能够在侧边栏中显示 Woocommerce 产品,按标题排序。目前此小部件中唯一的排序选项是 日期、价格、随机和销售。

我能够在 class-wc-widget-products 的 2 个部分中添加标题排序选项。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' ),
                ),

这里:

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';
}

此自定义工作正常,但是:

我的问题: 我应该在哪里保存这个自定义的“class-wc-widget-products.php”文件以防止它在下一次 Woocommerce 更新时被覆盖?
或者... 有没有更优雅的方法来完成这个?谢谢!

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

通过"title"强制orderby的正确方法可以这样做:

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;
}

代码进入您的活动子主题(或主题)的 function.php 文件或任何插件文件。

这应该适合你。

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


官方文档:WooCommerce Action and Filter Hook Reference