WordPress教程

Woocommerce中隐藏指定具有某个自定义字段值的产品

阿里云

WooCommerce 中隐藏指定具有某个自定义字段值的产品,我们在电商网站开发时经常遇到这种要求,其实和上一篇文章 WooCommerce 根据用户角色隐藏指定分类的产品 没有太大的区别,至少查询内容不同而已,将其添加到主题的 functions.php 文件中:

  1. add_action( 'pre_get_posts', 'custom_pre_get_posts_query' );
  2. function custom_pre_get_posts_query( $q ) {
  3. if ( ! $q->is_main_query() ) return;
  4. if ( ! $q->is_post_type_archive() ) return;
  5. if ( ! is_admin() ) {
  6. $q->set( 'meta_query', array(array(
  7.     'key'       => '_stock_status',
  8. // 字段名称
  9.     'value'     => 'outofstock',
  10. // 字段值
  11.     'compare'   => 'NOT IN'
  12. )));
  13.  
  14. }
  15. remove_action( 'pre_get_posts', 'custom_pre_get_posts_query' );
  16. }
也想出现在这里?联系我们
创客主机

上面的代码就是在查询输出之前去除了,具有"缺货"字段(outofstock)的产品。当然页可以使用此方法排除每个产品分类代码如下:

  1. add_action( 'pre_get_posts', 'custom_pre_get_posts_query' );
  2. function custom_pre_get_posts_query( $q ) {
  3. if ( ! $q->is_main_query() ) return;
  4. if ( ! $q->is_post_type_archive() ) return;
  5. if ( ! is_admin() ) {
  6. $q->set( 'tax_query', array(array(
  7. 'taxonomy' => 'product_cat',
  8. 'field' => 'slug',
  9. 'terms' => array( 'PUT YOUR CATEGORY HERE' ),
  10. // Don't display products in the membership category on the shop page . For multiple category , separate it with comma.
  11. 'operator' => 'NOT IN'
  12. )));
  13.  
  14. }
  15. remove_action( 'pre_get_posts', 'custom_pre_get_posts_query' );
  16. }

Woocommerce 中隐藏指定具有某个自定义字段值的产品

已有 207 人购买
查看演示升级 VIP立刻购买

收藏
(0)

发表回复

热销模板

Ashade - 作品展示摄影相册WordPress汉化主题
LensNews

本站承接 WordPress / PbootCMS / DedeCMS 等
系统建站、仿站、开发、定制等业务!