WP_Query 关于 Woocommerce 产品有很多错误:
- 对于产品类别和产品属性,您最好通常使用
tax_query。
- 对于产品可见性,自 Woocommerce 3 起,它由
product_visibility 'exclude-from-search' 和 'exclude-from-catalog' 术语的分类法处理。
关于产品变体的重要说明:
- 产品类别(或产品标签)不由产品变体处理,而是由父变量产品处理
- 变体的产品属性作为发布元数据处理,
meta_key 前面带有“attribute_”和met_value,即术语段。
-
产品变体中未处理产品可见性,因为它们未显示在存档页面中。
- 它们不会显示在存档页面中(如前所述)。
因此,当使用WP_Query 时,您不能同时查询“产品”帖子类型和“product_variation”帖子类型因为它们确实不同。
要使您的查询适用于“product_variation”帖子类型,您需要一个小实用函数来获取产品类别的父变量产品(或任何自定义分类作为产品标签......):
// Utility function to get the parent variable product IDs for a any term of a taxonomy
function get_variation_parent_ids_from_term( $term, $taxonomy, $type ){
global $wpdb;
return $wpdb->get_col( "
SELECT DISTINCT p.ID
FROM {$wpdb->prefix}posts as p
INNER JOIN {$wpdb->prefix}posts as p2 ON p2.post_parent = p.ID
INNER JOIN {$wpdb->prefix}term_relationships as tr ON p.ID = tr.object_id
INNER JOIN {$wpdb->prefix}term_taxonomy as tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
INNER JOIN {$wpdb->prefix}terms as t ON tt.term_id = t.term_id
WHERE p.post_type = 'product'
AND p.post_status = 'publish'
AND p2.post_status = 'publish'
AND tt.taxonomy = '$taxonomy'
AND t.$type = '$term'
" );
}
代码进入您的活动子主题(或活动主题)的 function.php 文件中。测试和工作。 下面的WP_Query 需要…
此处WP_Query 代码用于产品变体 (仅)与特定产品类别和特定变体属性值相关:
// Settings
$cat_name = 'Apple'; // Product category name
$attr_taxonomy = 'pa_size'; // Product attribute
$attribute_term_slugs = array('39'); // <== Need to be term SLUGs
$query = new WP_Query( array(
'post_type' => 'product_variation',
'post_status' => 'publish',
'posts_per_page' => 100,
'post_parent__in' => get_variation_parent_ids_from_term( $cat_name, 'product_cat', 'name' ), // Variations
'meta_query' => array(
'relation' => 'AND',
array(
'key' => '_stock',
'value' => 0,
'compare' => '>'
),
array(
'key' => 'attribute_'.$attr_taxonomy, // Product variation attribute
'value' => $attribute_term_slugs, // Term slugs only
'compare' => 'IN',
),
),
) );
// Display the queried products count
echo '<p>Product count: ' . $query->post_count . '<p>';
// Displaying raw output for posts
print_pr($query->posts);
经过测试并且有效。