(Wordpress +自动填充)搜索标签并获取搜索标签的所有帖子列表?

I'm trying to build a wordpress search with a customized autocomplete suggestion list. I want to restrict the search to tags only and if the user types in a search query that fits any of the tags or multiple tags, the autocomplete list should return all posts, associated with this/these tag(s).

For example, typing in "Jazz" could give:

Jazz
  Post 1
  Post 2
  Post 3
  Post 4
  Post 5

Jazz House
  Post 1
  Post 2
  Post 3

Great Jazz Trio
  Post 1

…

There is one autocomplete example, working with categories. That might lead in the right direction, but here the search queries are the "posts" which will be listed under their categories. I'd need the user to search the categories (tags) to list all posts, associated with them.

I thought it might be possible to create an array of objects of all tags. And each object (tag) could contain all related posts. This array could serve as data-source for the autocomplete.

I'd be happy about any suggestions on how to approach that.

global $wpdb;

// search term provided by user
$s = 'jazz';

$query = '
SELECT wp.post_title AS label, wt.name AS category 
FROM `wp_posts` wp
INNER JOIN `wp_term_relationships` wtr ON (wp.`ID` = wtr.`object_id`)
INNER JOIN `wp_term_taxonomy` wtt ON (wtr.`term_taxonomy_id` = wtt.`term_taxonomy_id`)
INNER JOIN `wp_terms` wt ON (wt.`term_id` = wtt.`term_id`)
WHERE wp.post_type="post" AND wp.post_status="publish" AND wtt.taxonomy = "post_tag" AND wt.name LIKE "%%%s%%"
ORDER BY wt.name, wp.post_date DESC';

$posts = $wpdb->get_results( $wpdb->prepare( $query, $s ) );

If I'm not mistaken, your goal is to provide the data array to the jQuery UI Autocomplete plugin, as in this example. The fastest way ( in terms of performance ) to do that is to create a custom query that will join the wp_posts and wp_terms tables, depending on the search term provided by user. The result of the query, after conversion to json ( json_encode( $posts ) ), will be in the format suitable for autocomplete plugin:

[ 
    { label: "Post 1", category: "Great Jazz Trio" }, 
    { label: "Post 1", category: "Jazz" },
    { label: "Post 2", category: "Jazz" },
    { label: "Post 3", category: "Jazz" },
    { label: "Post 4", category: "Jazz" },
    { label: "Post 5", category: "Jazz" },
    { label: "Post 1", category: "Jazz House" },
    { label: "Post 2", category: "Jazz House" },
    { label: "Post 3", category: "Jazz House" }
]

Sir,

You can use this plugin

https://wordpress.org/plugins/search-autocomplete/

It will support custom post types too. done with jquery ui