【问题标题】:Excluding posts on WooCommerce 'shop order' archive page based on meta key/value根据元键/值排除 WooCommerce“商店订单”存档页面上的帖子
【发布时间】:2018-05-10 18:57:17
【问题描述】:

我正在尝试从车间订单页面中排除某些帖子,例如'/wp-admin/edit.php?post_type=shop_order' 如果存在某个 meta_key/meta_value 组合。

我尝试了两种方法,但似乎都无法正常工作:

选项 1:预先获取帖子

add_action( 'pre_get_posts', 'so_filter_shop_order' );

function so_filter_shop_order($query) {

    global $typenow;

    /** @var $query WP_Query */

    if ($query->is_main_query() && $typenow === 'shop_order' && is_admin()) {

        $query->set( 'meta_key', '_method_created' );
        $query->set( 'meta_value', 'booking' );
    }

}

选项 1 的限制 这个选项的问题是它似乎没有针对此页面上的其他查询(例如,不同帖子状态的计数)。我还担心这段代码会针对其他地方的其他查询。

选项 2:过滤“请求”

这是我从 WooCommerce CSV 导出插件中得到的一个想法(因为他们也过滤了这个循环)。

add_filter( 'request', 'so_order_filters');

function so_order_filters( $vars ) {
    global $typenow;

    if ( 'shop_order' === $typenow ) {

        $vars['meta_key']   = '_method_created';
        $vars['meta_value'] = 'booking';
    }

    return $vars;
 }

选项 2 的限制 这种方法也不针对页面上的其他内容,并且还与 CSV 导出插件冲突,因为只能将一个 'meta_key' 添加到 $vars 数组中。我也 95% 确定这不是正确的做法。

我需要帮助的地方

如果哪一种方法值得采用或建议的替代方法是否值得获得一些反馈,那就太好了。

如果我可以在选项 1 中添加其他内容以确保它只针对正确的查询,这也是一件好事

最后,关于如何在页面上的其他相关查询中定位其他内容的任何建议都将非常有用。

提前致谢。

【问题讨论】:

    标签: php wordpress woocommerce


    【解决方案1】:

    这是另一种方法。

    1. 通过SQL获取所有具有特定元键+元值组合的帖子ID。

    2. 使用 post__in 参数包含它。

       add_action( 'pre_get_posts', 'so_filter_shop_order' );
      
       function so_filter_shop_order($query) {
      
          global $wpdb;$excluded_results=array();
          $excluded_results=$wpdb->query("select post_id from $wpdb->postmeta where meta_key='_method_created' and meta_value='booking' ");
          foreach ($variable as $key => $value) {$excluded_results[]=$value;}
      
          if (strpos($_SERVER["REQUEST_URI"],'post_type=shop_order') && is_admin()) {
              $query->set( 'post__in',  $excluded_results);
          }
      }
      

    pre_get_posts 无法影响显示帖子数量的表头部分。它通过 wp_count_posts 过滤器工作。所以你需要为此创建一个过滤器。这是示例样板:

    add_filter('wp_count_posts','changenumbers',0,3);
    function changenumbers ($counts, $type, $perm){
     if (strpos($_SERVER["REQUEST_URI"],'post_type=product') && is_admin()) {
                    $counts->publish=0;
                    //var_dump($counts);
                    //you need to write some wp_query there which would get the number of posts by their status. Then you will only need to return those values.
                }
                return $counts;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-27
      • 1970-01-01
      • 2014-04-24
      • 2020-05-05
      • 2020-01-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多