【问题标题】:WooCommerce get products by attribute queryWooCommerce 通过属性查询获取产品
【发布时间】:2018-01-31 09:22:28
【问题描述】:

我有一个带有属性颜色的产品。属性值为红色、蓝色和绿色。我正在尝试创建自定义搜索,但无法通过查询获取任何产品。

$args =  array(
    'post_type'      => array('product'),
    'post_status'    => 'publish',
    'posts_per_page' => -1,
    'meta_query'     => array( 
        array(
            'key' => '_visibility',
            'value' => array('catalog', 'visible'),
            'compare' => 'IN',  
        ) 
    ),
    'tax_query'      => array( 
        array(
            'taxonomy'        => 'product',
            'field'           => 'slug',
            'terms'           =>  array('blue', 'red', 'green'),
            'operator'        => 'IN',
        ),
    )
);

$products = new WP_Query( $args );

我哪里做错了?

【问题讨论】:

    标签: php wordpress woocommerce attributes product


    【解决方案1】:

    产品属性颜色的正确分类是 'pa_color',因此正确的工作查询是:

    // The query
    $products = new WP_Query( array(
       'post_type'      => array('product'),
       'post_status'    => 'publish',
       'posts_per_page' => -1,
       'meta_query'     => array( array(
            'key' => '_visibility',
            'value' => array('catalog', 'visible'),
            'compare' => 'IN',
        ) ),
       'tax_query'      => array( array(
            'taxonomy'        => 'pa_color',
            'field'           => 'slug',
            'terms'           =>  array('blue', 'red', 'green'),
            'operator'        => 'IN',
        ) )
    ) );
    
    // The Loop
    if ( $products->have_posts() ): while ( $products->have_posts() ):
        $products->the_post();
        $product_ids[] = $products->post->ID;
    endwhile;
        wp_reset_postdata();
    endif;
    
    // TEST: Output the Products IDs
    print_r($product_ids);
    

    此代码已经过测试并且可以工作。您将获得所有具有颜色属性的产品,其值(术语)为“蓝色”、“红色”和“绿色”……

    自 WooCommerce 3 起,产品可见性由自定义分类法 product_visibility 处理。您可以看到以下相关线程:

    【讨论】:

    • 不幸的是,这对我不起作用,我不明白为什么。
    • @user3098629 我已经在我的测试服务器上对其进行了测试,对我来说它非常有效。无论如何,属性“颜色”的正确分类是pa_color。所有产品属性分类蛞蝓总是以pa_ ...
    • 实际产品中是否有任何需要设置才能使其工作的东西?我有一个可见的产品,除了这个查询之外,它会在其他任何地方显示。
    • 我得到了它的工作......显然元查询导致问题并导致它什么都不返回。感谢您的帮助
    • 由于 Woocommerce 3 你不再使用meta_query 排除隐藏产品,你将需要使用tax_query 详细在这里wordpress.stackexchange.com/questions/231118/…
    猜你喜欢
    • 1970-01-01
    • 2018-12-24
    • 1970-01-01
    • 2019-04-30
    • 1970-01-01
    • 2016-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多