使用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_
”和“ slugmet_value
”一词。因此,在使用时WP_Query
,您不能同时查询“ product”帖子类型和“ product_variation”帖子类型,因为它们实际上是不同的。
为了使您的查询适用于“ product_variation”帖子类型,您需要一个小的实用程序函数,该函数将获取产品类别的父变量product (或任何自定义分类法作为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);
经过测试和工作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句