使用WooCommerce产品归档循环时,如何排除其变体具有某些元的产品?

时间:2020-10-15 21:55:05

标签: wordpress woocommerce hook-woocommerce

我一直在广泛研究wp_query和论坛,但尚未找到所需的宝石。

在查看从WooCommerce的archive-product.php中提取的产品归档页面时,我需要排除具有任何变体且后置元键“ variation_my_template”设置为字符串“ 0”的产品。 >或元键“ variation_my_template”未设置。

我一直在搞“ woocommerce_product_query”操作,这似乎是一个很好的起点。

add_action('woocommerce_product_query', 'hide_products_without_templates');
function hide_products_without_templates($q){
  $meta_query = $q->get('meta_query');
  $meta_query[] = [
    'key' => 'variation_my_template',
    'value' => '0',
    'compare' => '!='
  ];
  $q->set('meta_query',$meta_query);
}

问题在于,这只是检查父级产品的密钥,而不是其变体。我需要排除所有具有variant_my_template元设置为“ 0”或未设置的变体的产品。

关于获取和检查变异并在符合我的标准后排除其父母的最佳方法的任何方向都是有帮助的!

1 个答案:

答案 0 :(得分:0)

我能够通过运行另一个查询并使用该查询从原始/主查询中排除某些帖子来解决此问题。

add_action('woocommerce_product_query', 'hide_products_without_templates');
function hide_products_without_templates($q){
        $parentsToExclude = $q->get('post__not_in');

        $query = new WP_Query ([
            'post_type' => 'product_variation',
            'posts_per_page' => -1,
            'meta_query'    => [
                'relation' => 'OR',
                [
                    'key' => 'variable_my_template',
                    'compare' => 'NOT EXISTS',
                    'fields'    => 'slug',
                ],
                [
                    'key' => 'variable_my_template',
                    'value' => '',
                    'fields'    => 'slug',
                    'type'  => 'string',
                ],
                [
                    'key' => 'variable_my_template',
                    'value' => 0,
                    'fields'    => 'slug',
                    'type'  => 'NUMERIC',
                ],
            ],
        ]);
        $results = array();
        if($query->have_posts()){
            while ($query->have_posts()) {
                $query->next_post();
                $results[] = $query->post;
            }
            wp_reset_postdata();
        }
        wp_reset_query();
        foreach( $results as $product) {
            $parent_id = wp_get_post_parent_id($product->ID);
            if(!in_array($parent_id,$parentsToExclude)) $parentsToExclude[] = $parent_id;
        }
        error_log('POSTS:');
        error_log(print_r($parentsToExclude,true));
        $q->set('post__not_in',$parentsToExclude);
}