按自定义产品属性过滤产品并在WP_Query中发布元数据

时间:2019-01-02 10:48:32

标签: php wordpress loops woocommerce product

我已经按类别进行了过滤,但是不知道如何通过自定义属性或元值来过滤产品

代码:

$key="naam"; //custom attribute name
$value="test";// custom value
$query_custom = array('key' => $key, 'value' => $value);
$meta_query[] = $query_custom ;

$args=array('meta_query'=>$meta_query, 'product_cat' => 'activiteiten','posts_per_page' => 10,'post_type' => 'product');



$loop = new WP_Query( $args );

`

See image for custom attributes

2 个答案:

答案 0 :(得分:1)

您可以使用以下代码实现。

            $args = array(
              'meta_query'=> array(
                array(
                  'key' => 'vote', // here use your field name
                  'compare' => '=', // comparison sign
                  'value' => 5, // value using that you can search

                )
              ),
              'product_cat' => 'activiteiten',
              'posts_per_page' => 10,
              'post_type' => 'product'
            ) );

            query_posts( $args ); // get all the posts data using above filter.

query_posts用于查找带有参数列表的帖子meta_query用于查找匹配的自定义字段数据。

答案 1 :(得分:1)

以下是涉及以下内容的有效查询示例:

  • 产品类别过滤
  • 元数据后过滤(元查询)
  • 产品属性值过滤(税收查询)

代码:

$products = new WP_Query( array(
    'posts_per_page' => 10,
    'post_type'   => 'product',
    'post_status' => 'publish',

    // 1. Product category filter
    'product_cat' => 'clothing',

    // 2. The Post meta query part (filtering by post meta value)
    'meta_query' => array( array(
         'key'     => '_price',
         'value'   => 5,
         'type'    => 'numeric',
         'compare' => '>',
    ), ),

    // 3. The taxonomy meta query part (filtering by term values)
    'tax_query' => array( array(
        'taxonomy' => 'pa_color', // Product attribute taxonomy: always start with 'pa_'
        'field'    => 'slug', // Can be 'term_id', 'slug' or 'name'
        'terms'    => array('blue'),
    ), ),
) );

// Testing output
if( $products->have_posts() ) : 
echo '<ul>'
while ( $products->have_posts() ) : $products->the_post();
echo '<li class="post-id-' . get_the_id() . '">' . get_the_title() . '</li>';
endwhile;
wp_reset_postdata();
echo '</ul>'
endif;

经过测试,可以正常工作:

Wordpress WP_Query的官方参考文档:

相关问题