[英]Hide category in the WooCommerce shop page
我一直在嘗試從 SHOP 頁面隱藏特定類別。 我找到了這個代碼:
add_filter( '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;
$q->set( 'tax_query', array(array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => array( 'CATEGORY TO HIDE' ),
'operator' => 'NOT IN'
)));
remove_filter( 'pre_get_posts', 'custom_pre_get_posts_query' );
}
我已將此代碼粘貼到我的主題 function.php 文件中,但沒有達到結果...
有人可以幫我嗎?
我知道這有點晚了,但是我自己遇到了這個問題並使用以下功能解決了它:
add_filter( 'get_terms', 'get_subcategory_terms', 10, 3 );
function get_subcategory_terms( $terms, $taxonomies, $args ) {
$new_terms = array();
// if 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( '**CATEGORY-HERE**' ) ) ) {
$new_terms[] = $term;
}
}
$terms = $new_terms;
}
return $terms;
}
以下代碼段對我來說很好用:
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( 'your category slug' ), // Don't display products in the knives category on the shop page
'operator' => 'NOT IN'
)));
}
remove_action( 'pre_get_posts', 'custom_pre_get_posts_query' );
}
我想知道如何才能通過產品搜索來搜索排除在類別中的產品,同時使用代碼段這些產品完全隱藏。
從管理后端之外的所有內容中隱藏類別的簡單方法:
在functions.php
:
add_filter( 'get_terms', 'hide_category', 10, 1 );
function hide_category( $terms ) {
$new_terms = array();
foreach ( $terms as $term ) {
if ( $term->slug !== 'secret_category' ) {
$new_terms[] = $term;
} else if ( $term->taxonomy !== 'product_cat' || is_admin() ) {
$new_terms[] = $term;
}
}
return $new_terms;
}
如果您只想將其隱藏在商店中,請添加|| !is_shop()
|| !is_shop()
到else if
條件。
如果你想在你的主題中隱藏一些類別,你可以在wp_list_categories
函數中傳遞exclude
參數:
wp_list_categories( array(
'taxonomy' => 'product_cat',
'hide_empty' => 1,
'use_desc_for_title' => 0,
'title_li' => ' ',
'show_count' => 0,
'exclude' => '63' // <-- Hidden) );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.