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

查看:238
本文介绍了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?

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

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天全站免登陆