Skip to content

Instantly share code, notes, and snippets.

@msaari
Created November 7, 2017 04:37
Show Gist options
  • Select an option

  • Save msaari/3f2008ab5ffbb3a421dce616641fd8d1 to your computer and use it in GitHub Desktop.

Select an option

Save msaari/3f2008ab5ffbb3a421dce616641fd8d1 to your computer and use it in GitHub Desktop.
Relevanssi AJAX search
<?php
add_action('wp_ajax_relevanssi_search', 'rlv_ajax_search');
add_action('wp_ajax_nopriv_relevanssi_search', 'rlv_ajax_search');
function rlv_ajax_search() {
$query = new WP_Query();
$query->set('s', $_POST['s']);
/* Any other parameters you want to set, for example:
$query->set('post_types', 'page');
$query->set('numberposts', 100);
*/
$posts = relevanssi_do_query($query);
echo json_encode($posts);
wp_die();
}
/* the jQuery code */
var search_term = $("#s").value(); // or wherever you get the search term
var data = {
'action': 'relevanssi_search',
's': search_term
}
jQuery.post(ajaxurl, data, function(response) {
results = JSON.parse(response);
};
/*
That's about it, this is how I would approach this.
Remember that ajaxurl is not defined on the front-end by default:
https://codex.wordpress.org/AJAX_in_Plugins#Ajax_on_the_Viewer-Facing_Side
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment