WooCommerce:将自定义过滤器添加到产品管理区域

时间:2015-12-07 14:21:49

标签: php wordpress woocommerce

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

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

由于

1 个答案:

答案 0 :(得分:4)

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

添加过滤器

首先,您需要使用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的不同方面。