在WooCommerce *(最新版本)*我有一个变量产品withId:9`.
通过下面的变体属性,我创建了多个产品变体.
然后我想从父产品ID(Id:9)和以下属性值获得特定的产品变体:
<attribute_for_variation>: <attribute_value_to_filter>
pa_size: size_8x10
pa_material: mat_luster_photo_paper
pa_frame: fra_silver_wood
pa_mat_usage: musa_yes
您可以在下面看到该变体的屏幕截图:
我尝试了以下代码及其相应的结果.
为简单起见,现在只尝试使用pa_frame属性.
试试1:
static function filterVariations() {
$query = [
'post_parent' => 9,
'post_status' => 'publish',
'post_type' => ['product_variation'],
'posts_per_page' => -1,
];
$result = [];
$wc_query = new \WP_Query($query);
while ($wc_query->have_posts()) {
$wc_query->next_post();
$result[] = $wc_query->post;
}
return $result;
}
// ---> RESULT: all the variations, that's OK
试试2:
static function filterVariations() {
$query = [
'post_parent' => 9,
'post_status' => 'publish',
'post_type' => ['product_variation'],
'posts_per_page' => -1,
'tax_query' => [
'relation' => 'AND',
[
'taxonomy' => 'pa_frame',
'field' => 'slug',
'terms' => [ 'fra_silver_wood' ],
],
],
];
$result = [];
$wc_query = new \WP_Query($query);
while ($wc_query->have_posts()) {
$wc_query->next_post();
$result[] = $wc_query->post;
}
return $result;
}
// ---> RESULT: empty list
有关如何使用特定属性值返回所有变体的任何想法?
解决方法:
变量产品中的产品属性在wp_postMeta数据库表中设置为元数据.然后,您将需要使用Meta查询而不是Tax查询.试试这个:
static function filterVariations() {
$query = new \WP_Query( array(
'post_parent' => 9,
'post_status' => 'publish',
'post_type' => 'product_variation',
'posts_per_page' => -1,
'Meta_query' => array( array(
'key' => 'attribute_pa_frame',
'value' => 'fra_silver_wood',
) ),
) );
$result = array();
if($query->have_posts()){
while ($query->have_posts()) {
$query->next_post();
$result[] = $query->post;
}
wp_reset_postdata();
}
wp_reset_query();
return $result;
}
这应该按预期工作……
对于您的问题中列出的多个产品属性对(键/值),您只需在WP_Query中使用它们:
public function filterVariations() {
$query = new \WP_Query( array(
'post_parent' => 40,
'post_status' => 'publish',
'post_type' => 'product_variation',
'posts_per_page' => -1,
'Meta_query' => array(
array(
'key' => 'attribute_pa_size',
'value' => 'size_8x10',
),
array(
'key' => 'attribute_pa_material',
'value' => 'mat_luster_photo_paper',
),
array(
'key' => 'attribute_pa_frame',
'value' => 'fra_silver_wood',
),
array(
'key' => 'attribute_pa_mat_usage',
'value' => 'musa_yes',
),
),
) );
$result = array();
if($query->have_posts()){
while ($query->have_posts()) {
$query->next_post();
$result[] = $query->post;
}
wp_reset_postdata();
}
wp_reset_query();
return $result;
}
然后你会得到相应的产品变化(只有一个)……
Note: product attributes Meta keys start all with
attribute_pa_
instead of justpa_
文档:WP_Query and Custom Field Parameters (meta query)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。