在页面上显示Woocommerce中特定价格以下的所有产品

问题描述 投票:0回答:2

我有一家拥有超过1000种产品的Woocommerce商店。我想所有价格低于999的产品都应该显示在一个单独的页面上,所以我可以在菜单中标记该页面。

可能吗?

php wordpress woocommerce shortcode price
2个回答
0
投票

更新:(将'type' => 'DECIMAL',添加到meta_query阵列)

这可以使用Woocommerce shortcode [products]在页面上使用,使用以下附加代码(这将增加定义要通过现有参数进行比较的价格的可能性):

add_filter( 'woocommerce_shortcode_products_query', 'products_based_on_price', 10, 3 );
function products_based_on_price( $query_args, $atts, $loop_name ) {
    if( ! ( isset($atts['class']) && ! empty($atts['class']) ) )
        return $query_args;

    if (strpos($atts['class'], 'below-') !== false) {
        $compare   = '<';
        $slug    = 'below-';
    } elseif (strpos($atts['class'], 'above-') !== false) {
        $compare   = '<';
        $slug    = 'above-';
    }

    if( isset($compare) ) {
        $query_args['meta_query'][] = array(
            'key'     => '_price',
            'value'   => (float) str_replace($slug, '', $atts['class']),
            'type'    => 'DECIMAL',
            'compare' => $compare,
        );
    }
    return $query_args;
}

代码位于活动子主题(或活动主题)的function.php文件中。经过测试和工作。


用法:

这里我们使用未使用的class参数来传递价格和比较运算符。

1)显示产品以下特定金额(您的情况)

您将使用class参数值below-999粘贴以下短代码示例(对于价格低于999的产品):

[products limit="16" paginate="true" columns="4" class="below-999"]

wordpress页面文本内容编辑器:

enter image description here

你会得到:

enter image description here

2)显示产品超过特定金额

您将使用class参数值above-50粘贴以下短代码示例(对于价格高于50的产品):

[products limit="16" paginate="true" columns="4" class="above-50"]

可用的短代码参数和设置:Woocommerce shortcodes documentation


1
投票
  • 创建新的页面模板
  • 创建新页面,分配新页面模板
  • 在页面模板代码(或使用过滤器)之上,使用WP_query查询您的产品

看到:

$query = new \WP_Query(
    [
      'posts_per_page' => -1,
      'post_type' => 'product',
      'meta_key' => '_price',
      'meta_value' => 999,
      'meta_compare' => '<',
      'meta_type' => 'NUMERIC'
    ]);
  • 然后,您可以使用while循环或foreach on $query->posts来显示您的帖子
© www.soinside.com 2019 - 2024. All rights reserved.