仅当父产品已发布时如何获取产品变体
How to get product variations only if the parent product is published
我进行了自定义查询以获取产品变体,但是当我丢弃某个产品时,它的变体状态将保持 publish
,因此如果客户尝试这样做,它会响应 404
错误查看废弃的产品变体。
那么,如何过滤这些变体以仅获取已发布父产品的变体?
我的代码:
<?php
$args = ['post_type' => ['product_variation'],
'orderby' => 'meta_value_num',
'order' => 'DESC',
'post_status'=>'publish',
'product_type'=>'variation',
'meta_query' => [
[
'key' => 'attribute_pa_flower-type',
'value' => $flower_type,
'compare' => '=',
]
]
];
?>
<?php $the_query = new WP_Query( $args );?>
<?php if ( $the_query->have_posts() ) : ?>
<div class="boxes">
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
...
做这样的事情:
//to hold the published product id which has vriation.
$has_variable_ids = [];
$args_parent = [
'post_type' => ['product'],
'post_status' => 'publish',
'posts_per_page' => -1
];
$pubished_post = new WP_Query($args_parent);
if (!empty($pubished_post->posts))
{
foreach ($pubished_post->posts as $post)
{
$_product = wc_get_product($post->ID);
if ($_product->is_type('variable'))
{
// Product has variations
$has_variable_ids[] = $post->ID;
}
}
}
$args = [
'post_type' => ['product_variation'],
'orderby' => 'meta_value_num',
'order' => 'DESC',
'post_status' => 'publish',
'post_parent__in' => $has_variable_ids,
'meta_query' => [
[
'key' => 'attribute_pa_flower-type',
'value' => $flower_type,
'compare' => '=',
]
]
];
$the_query = new WP_Query($args);
请注意:我还没有测试过,但应该可以。
希望对您有所帮助!
我进行了自定义查询以获取产品变体,但是当我丢弃某个产品时,它的变体状态将保持 publish
,因此如果客户尝试这样做,它会响应 404
错误查看废弃的产品变体。
那么,如何过滤这些变体以仅获取已发布父产品的变体?
我的代码:
<?php
$args = ['post_type' => ['product_variation'],
'orderby' => 'meta_value_num',
'order' => 'DESC',
'post_status'=>'publish',
'product_type'=>'variation',
'meta_query' => [
[
'key' => 'attribute_pa_flower-type',
'value' => $flower_type,
'compare' => '=',
]
]
];
?>
<?php $the_query = new WP_Query( $args );?>
<?php if ( $the_query->have_posts() ) : ?>
<div class="boxes">
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
...
做这样的事情:
//to hold the published product id which has vriation.
$has_variable_ids = [];
$args_parent = [
'post_type' => ['product'],
'post_status' => 'publish',
'posts_per_page' => -1
];
$pubished_post = new WP_Query($args_parent);
if (!empty($pubished_post->posts))
{
foreach ($pubished_post->posts as $post)
{
$_product = wc_get_product($post->ID);
if ($_product->is_type('variable'))
{
// Product has variations
$has_variable_ids[] = $post->ID;
}
}
}
$args = [
'post_type' => ['product_variation'],
'orderby' => 'meta_value_num',
'order' => 'DESC',
'post_status' => 'publish',
'post_parent__in' => $has_variable_ids,
'meta_query' => [
[
'key' => 'attribute_pa_flower-type',
'value' => $flower_type,
'compare' => '=',
]
]
];
$the_query = new WP_Query($args);
请注意:我还没有测试过,但应该可以。
希望对您有所帮助!