【问题标题】:WooCommerce: Adding a custom filter to the Product Admin areaWooCommerce:向产品管理区域添加自定义过滤器
【发布时间】:2018-12-07 04:23:07
【问题描述】:

我最近使用以下过滤器和操作组合在 WooCommerce 管理员的产品管理部分添加了一个列:manage_product_posts_columnsmanage_product_posts_custom_column

我的问题是,是否有一个钩子可以让我不为此列添加过滤器?我找不到,但我确定有可能?

谢谢

【问题讨论】:

    标签: php wordpress woocommerce


    【解决方案1】:

    您的问题非常模糊,因此我假设您的自定义列显示每个产品的元信息。


    添加过滤器

    首先,您需要使用restrict_manage_posts WordPress 操作将您自己的字段添加到“产品”管理页面顶部的“过滤器”区域:

    function my_custom_product_filters( $post_type ) {
    
    $value1 = '';
    $value2 = '';
    
    // Check if filter has been applied already so we can adjust the input element accordingly
    
    if( isset( $_GET['my_filter'] ) ) {
    
      switch( $_GET['my_filter'] ) {
    
        // We will add the "selected" attribute to the appropriate <option> if the filter has already been applied
        case 'value1':
          $value1 = ' selected';
          break;
    
        case 'value2':
          $value2 = ' selected';
          break;
    
      }
    
    }
    
    // Check this is the products screen
    if( $post_type == 'product' ) {
    
      // Add your filter input here. Make sure the input name matches the $_GET value you are checking above.
      echo '<select name="my_filter">';
    
        echo '<option value>Show all value types</option>';
        echo '<option value="value1"' . $value1 . '>First value</option>';
        echo '<option value="value2"' . $value2 . '>Second value</option>';
    
      echo '</select>';
    
    }
    
    }
    
    add_action( 'restrict_manage_posts', 'my_custom_product_filters' );
    

    注意:从 WP4.4 开始,此操作提供$post_type 作为参数,因此您可以轻松识别正在查看的帖子类型。在 WP4.4 之前,您需要使用$typenow 全局或get_current_screen() 函数来检查这一点。 This Gist offers a good example.


    应用过滤器

    为了使过滤器真正起作用,我们需要在加载“产品”管理页面时向 WP_Query 添加一些额外的参数。为此,我们需要像这样使用pre_get_posts WordPress 操作:

    function apply_my_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['my_filter'] ) && $_GET['my_filter'] != '' && $_GET['post_type'] == 'product' ) {
    
      // Create meta query array and add to WP_Query
      $meta_key_query = array(
        array(
          'key'     => '_my_meta_value',
          'value'   => esc_attr( $_GET['my_filter'] ),
        )
      );
      $query->set( 'meta_query', $meta_key_query );
    
    }
    
    }
    
    add_action( 'pre_get_posts', 'apply_my_custom_product_filters' );
    

    这是自定义过滤器的基础,它适用于任何帖子类型(包括 WooCommerce shop_orders)。您还可以为元查询(以及任何其他可用选项)设置“比较”值,或者根据需要调整 WP_Query 的不同方面。

    【讨论】:

    • 您现在可以添加更多链接到您的说明中:)
    • 非常感谢! @Cameron,你的代码 sn-ps 工作 100%。
    猜你喜欢
    • 1970-01-01
    • 2019-05-14
    • 1970-01-01
    • 2022-11-05
    • 2020-08-29
    • 1970-01-01
    • 2019-06-28
    • 1970-01-01
    • 2015-07-12
    相关资源
    最近更新 更多