我需要显示每个产品,如果它是可变产品(例如多种颜色),则需要在商店页面上显示每个变体。
起初,我编写了自己的查询来检索产品中的所有变体:
$product = get_product();
global $variable_id;
global $color;
if ($product->product_type == "variable") {
$variations = $product->get_available_variations();
foreach ($variations as $variation) {
$color = $variation["attributes"]["attribute_pa_colour"];
$variable_id = $variation['variation_id'];
wc_get_template_part('content', 'product');
}
} else {
$variable_id = null;
$color = null;
wc_get_template_part('content', 'product');
}
我为变体设置了全局参数,然后在另一个模板文件中成功获得了正确的图像。
此解决方案的问题是分页已损坏(1 个产品出现多次)。
因此,我需要实现的是操纵主要产品查询以选择所有产品,其中具有变体的那些必须为每个变体出现一次,并具有正确的图像链接和变体值(我还需要主产品的信息以链接到正确的页面)。这可以通过Left Join
基于post_parent
.
这里的关键是保持默认的 woocommerce 行为。这是检索产品的 woocommerce 功能:
private function query_products( $args ) {
// Set base query arguments
$query_args = array(
'fields' => 'ids',
'post_type' => 'product',
'post_status' => 'publish',
'meta_query' => array(),
);
if ( ! empty( $args['type'] ) ) {
$types = explode( ',', $args['type'] );
$query_args['tax_query'] = array(
array(
'taxonomy' => 'product_type',
'field' => 'slug',
'terms' => $types,
),
);
unset( $args['type'] );
}
// Filter products by category
if ( ! empty( $args['category'] ) ) {
$query_args['product_cat'] = $args['category'];
}
// Filter by specific sku
if ( ! empty( $args['sku'] ) ) {
if ( ! is_array( $query_args['meta_query'] ) ) {
$query_args['meta_query'] = array();
}
$query_args['meta_query'][] = array(
'key' => '_sku',
'value' => $args['sku'],
'compare' => '='
);
$query_args['post_type'] = array( 'product', 'product_variation' );
}
$query_args = $this->merge_query_args( $query_args, $args );
return new WP_Query( $query_args );
}
所以基本上,我需要找到一种方法来覆盖这个函数,以便WP_Query
返回一个包含所有“简单”产品的对象和所有“可变”产品的每个变体的产品,同时传递的所有参数$args
继续工作。