WooCommerce:仅在商店中显示在售产品 [英] WooCommerce: Display ONLY on-sale products in Shop

查看:32
本文介绍了WooCommerce:仅在商店中显示在售产品的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个产品存档页面(通常是WooCommerce中的商店页面)但仅显示特价产品.基本上它应该使用与archive-product.php 中相同的模板布局.主菜单中将有一个指向此页面的链接.我该怎么做?

I need to create a products archive page (usually the Shop page in WooCommerce) but displays ONLY the ON SALE products. Basically it should use the same template layout as that in the archive-product.php. There will be a link in the main menu that will direct to this page. How do I go about this?

我设法过滤掉了 ON SALE 产品,下面的代码位于 if ( have_posts() ) : 行上方...

I managed to filter out the ON SALE products with the code below placed just above the if ( have_posts() ) : line...

$args = array(
    'post_type'      => 'product',
    'order'          => 'ASC',
    'paged'          => $paged,
    'meta_query'     => array(
        array(
            'key'           => '_sale_price',
            'value'         => 0,
            'compare'       => '>',
            'type'          => 'numeric'
        )
    )
);

query_posts( $args );

代码放在 archive-product.php副本中,我将其命名为 archive-product_sale.php 并作为 <强>页面模板.

The code is placed in a copy of archive-product.php which I named archive-product_sale.php and made as a page template.

但是,这仅适用于简单产品类型,我需要它同时适用于简单产品和可变产品类型.>

However, this only works for Simple products type and I need it to work for both Simple products and Variable products type.

推荐答案

@mirus 关于短代码的回答让我想到了检查 WooCommerce 如何仅查询在售商品.显然 WooCommerce 有一个 wc_get_product_ids_on_sale() 函数,它将返回在售商品的 ID.然后我们可以使用 post__in 参数轻松调整查询以仅返回那些特定项目.

@mirus' answer regarding the shortcode gave me the idea to check out how WooCommerce is querying only the on-sale items. Apparently WooCommerce has a wc_get_product_ids_on_sale() function that will return the IDs of the on-sale items. Then we can easily adjust the query using the post__in parameter to only return those specific items.

WooCommerce 在 class-wc-query.php 类中有一个 woocommerce_product_query 钩子,它允许我们在运行之前修改查询......它是在 pre_get_posts 上运行,这是修改查询的常用位置.使用 Woo 的钩子只是意味着您让他们处理有关何时应该应用此查询修改的大多数条件逻辑.

WooCommerce has a woocommerce_product_query hook in the class-wc-query.php class that allows for us to modify the query before it is run.... it is run on pre_get_posts which is the usual place for modifying the query. Using Woo's hook just means you let them handle the majority of the conditional logic about when this query modification should be applied.

add_action( 'woocommerce_product_query', 'so_20990199_product_query' );

function so_20990199_product_query( $q ){

    $product_ids_on_sale = wc_get_product_ids_on_sale();

    $q->set( 'post__in', $product_ids_on_sale );

}

这篇关于WooCommerce:仅在商店中显示在售产品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆