Lia*_*ell 0 php wordpress woocommerce
我最近使用以下过滤器和操作组合在 WooCommerce 管理中的“产品管理”部分添加了一列:manage_product_posts_columns, manage_product_posts_custom_column。
我的问题是,是否有一个钩子不允许我为此列添加过滤器?我找不到,但我确定有可能吗?
谢谢
你的问题很模糊,所以我假设你的自定义列显示每个产品的元信息。
首先,您需要使用restrict_manage_postsWordPress 操作将您自己的字段添加到“产品”管理页面顶部的“过滤器”区域:
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' );
Run Code Online (Sandbox Code Playgroud)
注意:从 WP4.4 开始,此操作$post_type作为参数提供,因此您可以轻松识别正在查看的帖子类型。在 WP4.4 之前,您需要使用$typenow全局或get_current_screen()函数来检查这一点。这个 Gist 提供了一个很好的例子。
为了使过滤器真正起作用,我们需要在加载“产品”管理页面时向 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' );
Run Code Online (Sandbox Code Playgroud)
这是自定义过滤器的基础知识,它适用于任何帖子类型(包括 WooCommerce shop_orders)。您还可以为元查询(以及任何其他可用选项)设置“比较”值,或者根据需要调整 WP_Query 的不同方面。