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

时间:2018-08-06 20:51:44

标签: php wordpress woocommerce shortcode price

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

有可能吗?

2 个答案:

答案 0 :(得分: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循环,或在$query->posts上使用foreach来显示您的帖子

答案 1 :(得分: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 (对于价格高于 { {1}}

50

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

相关问题