Gem*_*eme 2 php product variations custom-taxonomy woocommerce
通过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' => '>'
)
)
);
Run Code Online (Sandbox Code Playgroud)
但我无法在此查询中使用它.如果我删除'product_cat' => 'Apple',查询工作.为什么?
WP_Query关于Woocommerce产品有很多错误:
tax_query.product_visibility分类'exclude-from-search'和'exclude-from-catalog'术语处理.关于产品变化的重要说明:
meta_key由"前缀attribute_"和met_value那就是长期塞.因此,当使用a时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'
" );
}
Run Code Online (Sandbox Code Playgroud)
代码位于活动子主题(或活动主题)的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);
Run Code Online (Sandbox Code Playgroud)
经过测试和工作.
| 归档时间: |
|
| 查看次数: |
2183 次 |
| 最近记录: |