function my_website_datas(){
wp_enqueue_style(YOUR CSS link -- you must know this)
wp_enqueue_script('my-theme-js', get_theme_file_uri('/js/scripts-bundled.js'), NULL, 'v1' , TRUE );
wp_localize_script('my-theme-js', 'websiteData', array(
'root_url' => get_site_url(),
'nonce' => wp_create_nonce('wp_rest')
))
}
add_action('wp_enqueue_scripts','my_website_datas');
create new API route
add_action('rest_api_init', 'my_new_search_api');
function my_new_search_api(){
//3 args - the 1st and 2nd is the API route you will hook
// like search_route/v1/search?term= in your getJson
register_rest_route('search_route/v1','search', array(
'methods' => WP_REST_SERVER::READABLE,
'callback' => 'customSearchResults' // this is your below function
));
}
Create the callback function
function customSearchResults( $data ) {
/* Create you new Query */
$mainQuery = new WP_Query( array(
'post_type' => array('post','page','post_type1'),
's' => sanitize_text_field( $data['term']) // v1/search?term
));
// create your array to append if the user attempt to search for kind of taxonomy
$results = array(
'generalInfo' => array(),
'post_type1' => array()
);
while($mainQuery->have_posts()){
$mainQuery->the_post();
//here when the taxonomy matches it will append the data the in array above
if( get_post_type() == 'posts' OR get_post_type() == 'page'){
array_push($results['generalInfo'], array(
'title' => get_the_title(),
'permalink' => get_the_permalink(),
'postType' => get_post_type(),
'authorName' => get_the_author()
));
}
if( get_post_type() == 'post_type1'){
array_push($results['post_type1'], array(
'title' => get_the_title(),
'permalink' => get_the_permalink(),
'postType' => get_post_type(),
'authorName' => get_the_author()
));
}
return $results;
}
}
Next in your JS file
The code is too long you must guess this this.searchField.val() part haha
$.getJSON(websiteData.root_url + '/wp-json/university/v1/search?term=' +
this.searchField.val(), (results) => {
// now you can append the result to wherever element you want.
this.resultsDiv.html(`
<p> ${results} </p> `)
}
This code will work if you know what you are doing.
Hope this helps!