2016-05-17 50 views
0

在WooCommerce中,我檢查了選項「Visibility out of stock」,但我需要某些產品類別保持可見狀態,即使該選項被選中。在一個類別中顯示缺貨的產品

另一方面,主店不顯示該類別。爲此,我使用此代碼:

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('MYCATEGORY'), // Don't show this category. 
     'operator' => 'NOT IN' 
))); 
    } 

    remove_action('pre_get_posts', 'custom_pre_get_posts_query'); 
} 

因爲它可以做到這一點?

謝謝!

回答

1

這僅僅是一個快速的猜測,而不是測試,但你可以試着以類似:

global $product; 

$terms = wp_get_post_terms($post->ID, 'product_cat'); 
foreach ($terms as $term) $categories[] = $term->slug; 

$category_to_show = ‘MYCATEGORY’; 
if($categories) { 
    if(in_array($category_to_show, $categories) && !$product->is_in_stock()) { 
     apply_filters('woocommerce_product_is_visible', true, $product->id); 
    } 
} 
+0

這是在循環使用? –

+0

通過刪除post-> ID,您應該可以在函數文件中的函數中使用它。 然後你可以使用$ terms = wp_get_post_terms($ taxonomy ='product_cat'); 如果沒有,嘗試在循環中使用它,如content-product.php,你可以刪除全局產品,因爲它已經包含在該文件中 – assemblr

+0

這給了我一個錯誤警告:in_array()期望參數2是數組, null在344行的/functions.php中給出的,這行是這樣的:'if(in_array($ category_to_show,$ categories)&&!$ product-> is_in_stock()){'錯誤在哪裏?我找不到這個... –

相關問題