使用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_
"和a met_value
也就是 词条.所以当使用 WP_Query
你 不能查询 同时将 "product "的职位类型和 "product_variation "的职位类型联系起来 殊途同归.
为了使你的查询能够适用于 "product_variation "后类型,你需要一个小的实用函数,它将获得产品类别的父变量product。(或任何自定义分类法作为产品标签...):
// 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);
经测试,有效。