使用 Woocommerce,我正在尝试为产品类别为“Apple”的产品变体帖子类型制作 WP_Query。
$args = array(
'product_cat' => 'Apple',
'post_type' => array('product', 'product_variation'),
'post_status' => 'publish',
'key' => '_visibility',
'value' => 'visible',
'posts_per_page' => 100,
'taxonomy' => 'pa_size',
'meta_value' => '39',
'meta_query' => array(
array(
'key' => '_stock',
'value' => 0,
'compare' => '>'
)
)
);
但是我无法在此查询中使用它。如果我删除
'product_cat' => 'Apple'
,查询有效。为什么?
最佳答案
这个WP_Query
有很多错误关于 Woocommerce 产品:
tax_query
反而。 product_visibility
处理'exclude-from-search'
的分类法和 'exclude-from-catalog'
条款。 关于产品变体的重要说明:
meta_key
以“attribute_
”和met_value
开头那就是 术语 slug . 所以当使用
WP_Query
,你无法查询 同时“product”帖子类型和“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);
测试和工作。
关于php - 带有 Woocommerce 中产品类别的产品变体 WP_Query,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49342704/