首页 > 解决方案 > 在 WooCommerce 的商店页面上显示销售商品

问题描述

我试图找出一个直接链接来显示商店中的所有销售商品。URL 通常可以过滤掉特定的属性和查询,所以我希望这是可能的。到目前为止,没有运气。

我的结果出现了:没有找到产品。但确实有产品在售。

我尝试了以下方法:

add_filter( 'woocommerce_product_query_meta_query', 'filter_on_sale_products', 20, 1 );
function filter_on_sale_products( $meta_query ){
    if( isset($_GET['onsale']) && $_GET['onsale'] ){
        $meta_query[] = array(
            'key' => '_sale_price',
            'value' => 0,
            'compare' => '>'
        );
    }
    return $meta_query;
}

这应该通过 URL 返回所有销售项目:https ://www.example.com/shop/?onsale=1

任何意见,将不胜感激

标签: wordpresswoocommerceproductpriceshop

解决方案


您的代码包含一些非常小的错误。

您可以改用woocommerce_product_query动作挂钩。这应该足够了:

function action_woocommerce_product_query( $q ) {
    if ( is_admin() ) return;

    // Isset & NOT empty
    if ( isset( $_GET['onsale'] ) ) {
        // Equal to 1
        if ( $_GET['onsale'] == 1 ) {
            //  Function that returns an array containing the IDs of the products that are on sale.
            $product_ids_on_sale = wc_get_product_ids_on_sale();

            $q->set( 'post__in', $product_ids_on_sale );
        }
    }
}
add_action( 'woocommerce_product_query', 'action_woocommerce_product_query', 10, 1 );

推荐阅读