我解决了这个问题,只需粘贴代码就可以了functions.php
代码不会删除默认的按标题搜索。
请参见带有屏幕截图的示例
首先,添加自定义字段组Post Type is equal to Product 并添加一个具有字段标签和字段名称的新字段,如下所示
在产品编辑页面中显示的自定义字段中添加一些文本
在最后一步中,只需将代码添加到
function.php
并在数组中用逗号分隔字段名称
$custom_fields = array("_product_test");
function search_by_custom_field_for_admin( $search, &$wp_query ) {
global $wpdb, $pagenow;
$post_type = \'product\';
$custom_fields = array(
"_product_test",
);
if ( \'edit.php\' != $pagenow || !is_admin() || $wp_query->query[\'post_type\'] != $post_type ) {
return $search;
}
$get_post_ids = array();
foreach ($custom_fields as $custom_field_name) {
$args = array(
\'posts_per_page\' => -1,
\'post_type\' => $post_type,
\'meta_query\' => array(
array(
\'key\' => $custom_field_name,
\'value\' => $wp_query->query[\'s\'],
\'compare\' => \'LIKE\'
)
)
);
$posts = get_posts( $args );
if(!empty($posts)){
foreach($posts as $post){
$get_post_ids[] = $post->ID;
}
}
}
$wp_query->set(\'post__in\', $get_post_ids);
return $search;
}
add_filter( \'posts_search\', \'search_by_custom_field_for_admin\', 999, 2 );
更改后,您可以在屏幕截图中看到搜索结果