【问题标题】:Filter products by custom product attribute et post meta data in a WP_Query按自定义产品属性过滤产品并在 WP_Query 中发布元数据
【发布时间】:2019-05-29 00:28:34
【问题描述】:

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

代码:

$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 );

`

【问题讨论】:

    标签: php wordpress loops woocommerce product


    【解决方案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 在您的情况下用于查找匹配的自定义字段数据。

    【讨论】:

    • 不鼓励仅使用代码回答,因为它们没有为未来的读者提供太多信息,请对您所写的内容提供一些解释
    【解决方案2】:

    这是一个涉及以下查询的工作示例:

    • 产品类别过滤
    • 发布元值过滤(元查询)
    • 商品属性值过滤(税金查询)

    代码:

    $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

    【讨论】:

      猜你喜欢
      • 2018-09-08
      • 2016-02-20
      • 1970-01-01
      • 2011-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-13
      • 2018-11-28
      相关资源
      最近更新 更多