Admin search ACF relationship

时间:2015-04-28 作者:benc

我有一个自定义的帖子类型名称story. 它有一个名为\'select_artist\' 与名为artist.

story 编辑页面,我想使用搜索框搜索\'select_artist\' 标题目前,它只会在我搜索艺术家帖子ID时返回结果,但我希望能够搜索艺术家帖子标题。

有什么建议吗?

1 个回复
最合适的回答,由SO网友:Jan Beck 整理而成

下面是一段代码片段,它将执行您所描述的操作:

add_action( \'pre_get_posts\', \'wpsx_185734_acf_search_relationship\' );
function wpsx_185734_acf_search_relationship( $q ) {
  $screen = get_current_screen();
  $s = $q->get(\'s\');
  $post_type = $q->get(\'post_type\');

  // Be very selective when running code at the pre_get_posts hook
  if (
    ! is_admin() || empty( $s ) || ( isset( $screen->post_type ) &&
    \'story\' != $screen->post_type ) || \'story\' != $post_type
  ) {
    return;
  }

  // get all artists that match the search parameter $s
  $found_artists = get_posts( array(
    \'post_type\' => \'artist\',
    \'nopaging\' => true,
    \'s\' => $s,
    \'fields\' => \'ids\'
  ) );

  // build a meta query to include all posts that contains
  // the matching artist IDs in their custom fields
  $meta_query = array();
  foreach ( $found_artists as $artist_id ) {
    $meta_query[] = array(
      \'key\' => \'select_artist\', // name of custom field
      \'value\' => \'"\' . intval($artist_id) . \'"\',
      // ^^ matches exactly "123", not just 123. This prevents a match for "1234"
      \'compare\' => \'LIKE\'
    );
  }
  $q->set( \'meta_query\', $meta_query );
  $q->set( \'s\', \'\' ); // unset the original query parameter to avoid errors
}
上面的代码假设您已经注册了自定义帖子类型,并为故事帖子类型添加了一个名为“select\\u Artister”的ACF关系字段。

我创建了一个公共gist,其中还包含注册自定义帖子类型和字段组的代码,因此它将作为独立插件运行:https://gist.github.com/jancbeck/fdd8f0c796778f6263d0

结束

相关推荐