Woocommerce 订购 "on-sale first" 商店和档案中的产品

Wooocommerce order "on-sale first" products inside shop and archives

我需要通过首先设置“特价”产品来更改默认的 woocommerce 过滤器。该循环还必须包含非特价商品,但所有商品均按特价商品排序。

我尝试使用 pre_get_posts 但我找到了只过滤产品的方法(例如只显示特价产品),而不是 重新订购它。

我解决了这个问题,这里是解决方案,希望对其他人有用。

  /**
 * @param $q
 * Reorder products on sale first on default shop filter.
 *
 * @return void
 */
function evolve_on_sale_reorder_query( $q ) {
    $meta_query = $q->get( 'meta_query' );

    if ( ! isset( $_GET['orderby'] ) ) {
        $meta_query = array(
            'relation' => 'OR',
            array(
                'key'     => '_sale_price',
                'compare' => 'NOT EXISTS'
            ),
            array(
                'relation' => 'OR',
                array(
                    'key'     => '_sale_price',
                    'value'   => '',
                    'compare' => "="
                    // 'value'=>array(''),
                    // 'compare' => 'IN'
                ),
                array(
                    'key'     => '_sale_price',
                    'value'   => 0,
                    'compare' => '>=',
                    'type'    => 'numeric',
                )
            ),
        );

        $q->set( 'orderby', array( 'meta_value' => 'DESC', 'title' => 'ASC' ) );
    }

    $q->set( 'meta_query', $meta_query );


}

add_action( 'woocommerce_product_query', 'evolve_on_sale_reorder_query' );