Skip to content

Instantly share code, notes, and snippets.

@mrbobbybryant
Created August 27, 2015 15:58
Show Gist options
  • Save mrbobbybryant/cb5065a82f8e268e450c to your computer and use it in GitHub Desktop.
Save mrbobbybryant/cb5065a82f8e268e450c to your computer and use it in GitHub Desktop.
<?php
function autosearch_metabox_callback() {
$output = '<div id="added-posts"><ul><input type="hidden" value=" " id="autosearch_posts" name="autosearch_posts" /></ul></div>';
$output .= '<label for="autosearch" id="autosearch-label" >';
$output .= '<input type="text" id="autosearch" name="autosearch" size="80" />';
echo $output;
}
add_action( 'add_meta_boxes', 'wp_autosearch_add_metabox' );
function myprefix_autocomplete_suggestions(){
// Query for suggestions
$args = array(
's' => $_REQUEST['term']
);
$search_results = new WP_Query( $args );
// Initialise suggestions array
$suggestions = array();
$posts = $search_results->get_posts();
global $post;
foreach ($posts as $post) {
// Initialise suggestion array
$suggestion = array();
$suggestion['label'] = get_the_title();
$suggestion['link'] = get_permalink();
$suggestion[ 'id' ] = get_the_ID();
// Add suggestion to suggestions array
$suggestions[]= $suggestion;
}
wp_reset_postdata();
// JSON encode and echo
$response = $_GET["callback"] . "(" . json_encode($suggestions) . ")";
echo $response;
// Don't forget to exit!
exit;
}
add_action( 'wp_ajax_myprefix_autocompletesearch', 'myprefix_autocomplete_suggestions' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment