I need to know what query I have to use on the AJAX to get the output?
In the comments, you said, “I am looking to search only for categories“, so for that, you can simply use get_categories()
(or get_terms()
for custom taxonomies) and set the search
arg to the submitted search keyword:
// Get the categories assigned to ANY posts that matched the search keyword.
$terms = get_categories( array(
'search' => sanitize_text_field( $_REQUEST['universalSearchlist'] ),
) );
// Then display the categories or do whatever is necessary. (I used 'echo' for testing.)
foreach ( $terms as $term ) {
$cat_link = get_category_link( $term );
echo '<a href="' . esc_url( $cat_link ) . '">' . esc_html( $term->name ) . '</a><br>';
}
/* Or using get_terms():
$terms = get_terms( array(
'search' => sanitize_text_field( $_REQUEST['universalSearchlist'] ),
'taxonomy' => 'your_taxonomy',
) );
if ( ! is_wp_error( $terms ) ) {
foreach ( $terms as $term ) {
... your code.
}
}
*/
So there’s no need for WP_Query
unless if you wanted only the categories assigned to posts that matched the search keyword.
Additional Notes
-
Actually, I suggest you to use the REST API for searching the categories — e.g. you’d make your AJAX requests to
example.com/wp-json/wp/v2/categories?search=<keyword>
, but you can ask another question for that. -
In your
universalSearch()
function, you should callwp_die()
and there’s no need toreturn
anything (thewp_ajax_
hooks are action hooks, not filter hooks). -
You should really enqueue your scripts (
.js
) usingwp_enqueue_script()
and you should just use the default jQuery script that came bundled with WordPress. -
Your AJAX JS is not actually sending the search keyword to the server, so in addition to the
action
parameter, you should adduniversalSearchlist: $( this ).val()
to the second parameter for$.post()
.