在商店頁隱藏特定分類的商品(分類頁面不影響)

參考文章:Hide category in the WooCommerce shop page

add_action( 'pre_get_posts', 'custom_pre_get_posts_query' );

function custom_pre_get_posts_query( $q ) {

    if ( ! $q->is_main_query() ) return;
    if ( ! $q->is_post_type_archive() ) return;

    if ( ! is_admin() && is_shop() ) {

        $q->set( 'tax_query', array(array(
            'taxonomy' => 'product_cat',
            'field' => 'slug',
            'terms' => array( '分類slug' ), // 填寫分類slug
            'operator' => 'NOT IN'
        )));

    }

    remove_action( 'pre_get_posts', 'custom_pre_get_posts_query' );

}

在商店頁隱藏特定分類

add_filter( 'get_terms', 'ts_get_subcategory_terms', 10, 3 );
function ts_get_subcategory_terms( $terms, $taxonomies, $args ) {
	$new_terms = array();
	// if it is a product category and on the shop page
	
	if ( in_array( 'product_cat', $taxonomies ) && ! is_admin() &&is_shop() ) {
		foreach( $terms as $key => $term ) {
			if ( !in_array( $term->slug, array( '商品slug' ) ) ) { //pass the slug name here
				$new_terms[] = $term;
			}
		}
		$terms = $new_terms;
	}
	return $terms;
}

使用外掛隱藏特定分類

Hide Categories and Products for Woocommerce

最後修改日期: 2023 年 10 月 17 日

作者