Php 将Woocommerce产品从产品标签内的特定产品类别中排除

Php 将Woocommerce产品从产品标签内的特定产品类别中排除,php,wordpress,woocommerce,tags,product,Php,Wordpress,Woocommerce,Tags,Product,如何从“备件”类别中排除产品,以显示在woocommerce产品标签查询中?我想在/tags/中列出所有产品,但如果该产品在“备件”类别中,只需在那里用字体列出即可。我需要使用哪个函数 我在网上搜索了一下,但没有成功。在这个自定义函数中,连接了woocommerce\u product\u query\u tax\u query过滤器钩子,可以轻松完成 因此,“备件”产品类别slug中的所有产品都将被排除在产品标签归档页面之外 这是代码: add_filter( 'woocommerce_pro

如何从“备件”类别中排除产品,以显示在woocommerce产品标签查询中?我想在/tags/中列出所有产品,但如果该产品在“备件”类别中,只需在那里用字体列出即可。我需要使用哪个函数


我在网上搜索了一下,但没有成功。

在这个自定义函数中,连接了
woocommerce\u product\u query\u tax\u query
过滤器钩子,可以轻松完成

因此,
“备件”
产品类别slug中的所有产品都将被排除在产品标签归档页面之外

这是代码:

add_filter( 'woocommerce_product_query_tax_query', 'exclude_specific_product_category_query', 10, 2 );
function exclude_specific_product_category_query( $tax_query, $query ) {
    // Only on Product Tag archives pages
    if( is_admin() || ! is_product_tag() ) return $tax_query;

    // HERE Define your product category SLUGs to be excluded 
    $terms = array( 'spare-parts' ); // SLUGs only

    // The taxonomy for Product Categories
    $taxonomy = 'product_cat'; 

    // Add your criteria
    $tax_query[] = array(
        'taxonomy' => $taxonomy,
        'field'    => 'slug', // Or 'name' or 'term_id'
        'terms'    => $terms,
        'operator' => 'NOT IN', // Excluded
    );

    return $tax_query;
}
代码位于活动子主题(或主题)的function.php文件或任何插件文件中

测试和工作


因此,如果您需要在
WP\u查询中使用它,您将使用类似的
,其中您将排除一些产品类别并包括一些产品标签

在本例中,它将输出一个分隔的产品ID字符串:

// HERE Define your product category SLUGs to be excluded
$terms_cat = array( 'spare-parts' ); // SLUGs only

// HERE Define your product tag SLUGs to be included
$terms_tag = array( 'special', 'wear' ); // SLUGs only

// The taxonomies
$taxonomy_tag = 'product_tag'; // Product tag
$taxonomy_cat = 'product_cat'; // Product Category

// The Query
$loop = new WP_Query( array(
    'post_type' => 'product',
    'post_status' => 'publish',
    'posts_per_page' => -1,
    'order' => 'ASC',
    'tax_query' => array(
        'relation' => 'AND',
        array( // The tag query (Include)
            'taxonomy' => $taxonomy_tag,
            'field'    => 'slug',
            'terms'    => $terms_tag,
        ),
        array( // the category query (exclude)
            'taxonomy' => $taxonomy_cat,
            'field'    => 'slug', // Or 'name' or 'term_id'
            'terms'    => $terms_cat,
            'operator' => 'NOT IN', // Excluded
        ),
    )
));

if ( $loop->have_posts() ):
    while ( $loop->have_posts() ):
        $loop->the_post();
        $products_ids[] = $loop->post->ID; // Set the product Ids in an array
    endwhile;
endif;

// always reset the WP_Query
wp_reset_query();

// Convert the array in a string with all product Ids coma separated
$product_ids_string = implode( ', ', $products_ids );

// Output Ids
echo $product_ids_string;
测试和工作



相关文档:

您试图解决此问题的方法是什么?如果您计划使用MySQL,那么这些表是如何构造的?感谢您的快速回答,我得到了“endif;”代码的错误line@DigitalWhirlLLC我已经做了一个大的更新(我正在完成这个答案),并纠正了这个小错误…你现在有一切可以让它成为你的