I am new in WordPress and I trying to create a live search using ajax, I want when a user presses a button a box appears, and search results show in that box.
for doing this I created a folder in my theme folder called livesearch
in that folder I put a file called search-live.php
and the code in that file like this:
<?php
//echo $_GET['search'];
$test = GetMySearchResult($_GET['search']);
print_r($test);
and in my functions.php
file I create a function called GetMySearchResult
like this:
function GetMySearchResult($search){
global $wpdb;
$myrows = $wpdb->get_results( "SELECT * FROM wp_posts post_type = post ID LIKE %" . $search . "%" );
return $myrows;
}
add_action('init', 'GetMySearchResult');
and I send data to search-live.php
using ajax and code Like this:
<script>
var GetSearch = document.getElementById('search');
GetSearch.addEventListener("keyup", function(){
//InfoData = {slug:GetSearch.value}
$.ajax({
type: "GET",
url: '<?php echo get_site_url(); ?>/wp-content/themes/webranko/livesearch/search-live.php?search=' + GetSearch.value ,
data: '',
datatype: "html",
success: function(result) {
console.log(result);
}
});
});
</script>
I already $_GET['search'];
and everything it’s ok and I can see the result in my console but when I call GetMySearchResult($_GET['search'])
it gives me a fatal error like this:
Fatal error: Uncaught Error: Call to undefined function GetMySearchResult() in C:xampphtdocswebwp-contentthemeswebrankolivesearchsearch-live.php:3 Stack trace: #0 {main} thrown in C:xampphtdocswebwp-contentthemeswebrankolivesearchsearch-live.php on line 3
what I missed or what I do wrong?
Advertisement
Answer
For creating live search just need send a GET request to wp-json
no need to make a new query
just use this URL in ajax request:
<?php echo get_site_url(); ?>wp-json/wp/v2/posts?search=' + GetSearch.value
So ajax code should be like this:
<script>
var GetSearch = document.getElementById('search');
GetSearch.addEventListener("keyup", function(){
//InfoData = {slug:GetSearch.value}
$.ajax({
type: "GET",
url: '<?php echo get_site_url(); ?>wp-json/wp/v2/posts?search=' + GetSearch.value ,
data: '',
datatype: "html",
success: function(result) {
console.log(result);
}
});
});
</script>
and the HTML search input should be like this:
<input type="search" id="search" name="search" placeholder="search" autocomplete="off"/>
you must turn off the autocomplete of input