您可以使用以下自定义函数来获取简单产品和产品变体的 ID(不包括可变产品)。
此外,该函数仅通过根据指定为参数的产品类别过滤具有发布状态的产品返回。
该函数将返回一个包含产品 ID 的数组。
/**
* Gets the ids of simple products and product variations with the following criteria:
* - Only if the product is published;
* - Excludes variable products;
* - Products belong to a specific product category.
*
* @param mixed $term Term to search for.
* @param string $taxonomy Taxanomy in which to search for the term.
* @param string $type Type of term to search for. It can contain the following values: 'term_id', 'name' or 'slug'
*
* @return array Product IDs.
*/
function get_simple_products_and_product_variations_ids_by_cat( $term, $type = 'slug', $taxonomy = 'product_cat' ) {
global $wpdb;
$sql = "SELECT ID
FROM {$wpdb->prefix}posts
INNER JOIN {$wpdb->prefix}term_relationships as tr ON ( ID = tr.object_id OR post_parent = 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 post_type IN ( 'product', 'product_variation' )
AND post_status = 'publish'
AND ID NOT IN (
SELECT DISTINCT post_parent AS parent_id
FROM {$wpdb->prefix}posts
WHERE post_type = 'product_variation'
AND post_status = 'publish'
)
AND tt.taxonomy = '$taxonomy'
AND t.$type = '$term'";
$results = $wpdb->get_col( $sql );
return array_map( 'intval', $results );
}
代码已经过测试并且可以运行。将其添加到您的活动主题的 functions.php 中。
用法
- 根据产品类别ID(例如
30)过滤产品:
get_simple_products_and_product_variations_ids_by_cat( 30, 'term_id' );
- 按产品类别名称(例如
Red wines)过滤产品:
get_simple_products_and_product_variations_ids_by_cat( 'Red wines', 'name' );
- 根据产品类别标签(例如
red-wines)过滤产品:
get_simple_products_and_product_variations_ids_by_cat( 'red-wines', 'slug' );
回答
您只获得简单产品的原因是产品类别和产品变体之间没有关系。唯一的关系是与可变产品(产品变体的post_parent)。
你可以通过上面自定义函数的结果设置WP_Query类的post__in参数来获取产品,那么:
$args = array(
'nopaging' => true,
'posts_per_page' => -1,
'post_type' => array( 'product', 'product_variation' ),
'post__in' => get_simple_products_and_product_variations_ids_by_cat( 'fruit' ),
);
$loop = new WP_Query( $args );
if ( $loop->have_posts() ) {
while ( $loop->have_posts() ) {
$loop->the_post();
global $product;
// do stuff
}
}
相关答案