Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
827 views
in Technique[技术] by (71.8m points)

wordpress - Hide 'out of stock' products in Woocommerce

Under "Products" and "Inventory" I have checked the following setting: "Hide out of stock items from the catalog"

Now all sold out products are hidden in the archive/category view. So far so good.

The problem is that the hidden (out of stock) products are counted per page. So if there are 3 products that are sold out on the first page, only the ones in stock are showing (6).

It also seems that these "hidden" products still are searchable as well, and visible through the different widgets.

Any ideas how to fix this? I mean to REALLY hide products that are out of stock. Or do I need to manuallly remove them?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can try adding this to your theme's functions.php file:

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() ) {


$q->set( 'meta_query', array(array(
    'key'       => '_stock_status',
    'value'     => 'outofstock',
    'compare'   => 'NOT IN'
)));

}

remove_action( 'pre_get_posts', 'custom_pre_get_posts_query' );

}

I modified the code from this URL: http://www.wptaskforce.com/how-to-exclude-one-or-more-category-in-woocommerce-shop-page/

Saved here again just in case that site goes offline: (this code excludes certain product categories)

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() ) {

$q->set( 'tax_query', array(array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => array( 'PUT YOUR CATEGORY HERE' ), // Don't display products in the membership category on the shop page . For multiple category , separate it with comma.
'operator' => 'NOT IN'
)));

}



remove_action( 'pre_get_posts', 'custom_pre_get_posts_query' );

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...