How can I reuse the WordPress search form for a custom plugin / widget?

I need to develop a custom widget to display posts, based on their ID.
The user must be able to handpick posts. Right now, they can enter the post ID, but it is not convenient for them.

Is it possible to use the Search form that appears on the Post Edit interface when creating a hyperlink instead of brewing my own solution and reinvent the wheel ? Here is a screenshot of the interface.
In this example, the interface autopopulates via Ajax a list of posts relevant to the searched term.

the built-in ajax search form

1 Answer
1

I looked into doing the same thing and in the end opted for a custom solution using thickbox as being less complex. Could be it’s possible, but perhaps not worth the effort. The code is certainly not built for customisation as far as I could see.

  1. Open a thickbox modal with a search field
  2. Ajax search the post title with the user-entered search term
  3. Echo the results into the modal as a list/table of post title, adding the post ID as a data attribute e.g. to a checkbox if the user can choose multiple items
  4. When the user clicks the ‘select’ button, use js to get the checked items and put them in a list/table in the page with the post id in a hidden field that you can access when the post is saved.

A couple of other notes:

  • In my case searching the post title was sufficient, I used a custom query with $wpdb -> prefix . 'posts.post_title LIKE %s.
  • explode() and loop through each of the search terms, using each with '%' . $str . '%' in the query

Leave a Comment