【问题标题】:WooCommerce product filter for an attribute in the backend后端属性的 WooCommerce 产品过滤器
【发布时间】:2022-07-06 16:57:20
【问题描述】:

我想在后端的 WooCommerce 产品部分中有一个属性“品牌”的过滤器。

我正在使用以下代码:

function custom_woocommerce_product_filters( $output ) {
    global $wp_query;
    
    $output .= wc_product_dropdown_categories(
                    array(
                            'show_option_none' => 'Filter by brand',
                            'taxonomy' => 'pa_brand',
                            'name' => 'pa_brand',
                            'selected' => isset( $wp_query->query_vars['pa_brand'] ) ? $wp_query->query_vars['pa_brand'] : ''
                        )
                    );
        
    return $output;
}
add_filter( 'woocommerce_product_filters', 'custom_woocommerce_product_filters' );

此代码显示过滤器的下拉列表,其中包含所有品牌,但单击“过滤器”不会返回过滤后的产品。它只是显示所有产品。

有人可以帮忙吗?

谢谢

【问题讨论】:

    标签: wordpress woocommerce


    【解决方案1】:

    我最近发现您必须使用 pre_get_posts() 过滤器实际过滤结果,仅使用下拉菜单是不够的。在 stackoverflow 上搜索类似问题后,我能想出什么:

    // Filter woocommerce admin products by artist
    function apply_artist_custom_product_filters( $query ) {
    
    global $pagenow;
    
    // Ensure it is an edit.php admin page, the filter exists and has a value, and that it's the products page
    if ( $query->is_admin && $pagenow == 'edit.php' && isset( $_GET['pa_artist'] ) && $_GET['pa_artist'] != '' && $_GET['post_type'] == 'product' ) {
    
      // Create meta query array and add to WP_Query
      $meta_key_query = array(
        array(
          'taxonomy'     => 'pa_artist',
          'field' => 'slug',
          'terms'   => esc_attr( $_GET['pa_artist'] ),
          'operator' => 'IN',
        )
      );
      $query->set( 'tax_query', $meta_key_query );
    
    }
    }
        
    add_action( 'pre_get_posts', 'apply_artist_custom_product_filters' );
    

    完成大部分工作的 sn-p 可以在这里找到:WooCommerce: Adding a custom filter to the Product Admin area。我只是将元查询更改为税务查询。不确定这是否是最好的方法,但它对我有用。我想不通的是wc_product_dropdown_categories 的“选定”部分,对我来说,当我选择艺术家并点击过滤器时,过滤器可以工作,但不会保存选择。

    【讨论】:

    • 感谢您的回复@Daniel。你把我引向了正确的方向。我的研究还发现我们需要使用 pre_get_posts 钩子,但我的代码不起作用。我根据您的建议对其进行了修改,并且效果非常好。对于选定的部分,我相信您需要添加一个自定义查询变量,如下所示:function custom_query_vars( $vars ) { $vars[] = 'pa_brand'; return $vars; } add_filter( 'query_vars', 'custom_query_vars' ); 请让我知道它是否有效。谢谢!
    • 工作就像一个魅力!一百万年都不会想到这一点。非常感谢!
    【解决方案2】:

    您可以分享完整的代码,以便我可以在网站上输入它。谢谢

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-12
      • 1970-01-01
      • 2021-10-21
      • 2018-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多