I have a page where I show all the attachments of a page in a table which has id=10
.
I have hundreds of attachments and I would like to implement an AJAX search form that uses the title of attachment as key for search.
Actually the problem is not in implementing the AJAX call, but the query that returns the attachments list.
You should try applying the
s
(search) as parameter for your custom query.See this example here:
and you can then apply normal loop to iterate through your results. This also performs string match same as like operator
%keyword%
you mentioned in comment for @Ravs’ answer.Refer documentation here.
WP_Query
will not do what you want by default. If you try to search bypost_name
you will get apost_name=
query which is too strict. If you use thes
parameter you will get a%term%
search over both the post name and the post content andterm
will match anywhere in the word, not just at the beginning. And that is too broad for what you are doing. Ands
becomes increasingly less efficient as you add terms, though that may not be an issue for your.You say you want a match if you tyoue the “first n” letters, so you need to filter the query. This should do it.
You are searching the post name only and the filter adds a
%
to the right only so the wildcard match is only on right of the term.Add the filter in your AJAX callback before the query and it will remove itself automatically (though that last part probably is not necessary).
you query in may be like
Important Link:
get_posts()
Ajax Search Form