Woocommerce 在分類目錄中隱藏無庫存的商品
網路上有很多解決在 woocommerce 的分類目錄中,隱藏無庫存商品的方法,但都不合我用,只好自己動手寫一個適合的,設計的思維是,在取得商品的之前 (pre_get_posts) ,我們判斷商品是否已經無庫存,是的話,我們就把發布狀態設定為私密 (private),型錄可見度設定為「隱藏」
在 functions.php 中加入以下的程式碼
// 在目錄中隱藏無庫存的商品 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( 'sb00001' ), // 設定在那幾個目錄中要處理,多個目錄的話用逗號分隔 'operator' => 'NOT IN', 'post_status' => 'private', ))); } remove_action( 'pre_get_posts', 'custom_pre_get_posts_query' ); }
2022-03-28 更新
上面的寫法不一定成功,補充另一個寫法,只要在商品庫存量被變更的時候,去將商品的顯示狀態設定成隱藏起來就可以了
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() ) { global $wpdb; $results = $wpdb->get_results( 'SELECT * FROM `wp_aws_index` c WHERE c.id in (SELECT a.ID FROM `wp_posts` a join `wp_postmeta` b ON a.ID = b.post_id where b.meta_key = "_stock_status" and b.meta_value = "outofstock"); UPDATE `wp_aws_index` c SET c.visibility = "hidden" WHERE c.id in (SELECT a.ID FROM `wp_posts` a join `wp_postmeta` b ON a.ID = b.post_id where b.meta_key = "_stock_status" and b.meta_value = "outofstock"); DELETE FROM `wp_aws_cache`; delete from `wp_term_relationships` WHERE `term_taxonomy_id` = 7 AND `object_id` in (SELECT a.ID FROM `wp_posts` a join `wp_postmeta` b ON a.ID = b.post_id where b.meta_key = "_stock_status" and b.meta_value = "outofstock"); INSERT INTO `wp_term_relationships` (`object_id`, `term_taxonomy_id`) VALUES ((SELECT a.ID FROM `wp_posts` a join `wp_postmeta` b ON a.ID = b.post_id where b.meta_key = "_stock_status" and b.meta_value = "outofstock"), 7);' , OBJECT); remove_action( 'pre_get_posts', 'custom_pre_get_posts_query' ); }
近期留言