Created
May 21, 2014 07:13
-
-
Save prionkor/d1c978e0bd0edbee3a67 to your computer and use it in GitHub Desktop.
JSON Search Data Feed Plugin for Wordpress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
Plugin Name: WPSE Search Data Feed | |
Plugin URI: http://wordpress.stackexchange.com | |
Description: Provides interface to search and get result in JSON data | |
Author: Sisir | |
Version: 1.0 | |
Author URI: http://developerpage.net | |
*/ | |
add_action('wp_ajax_nopriv_wpse144893_search', 'wpse144893_search_data'); // allow logged out users | |
add_action('wp_ajax_wpse144893_search', 'wpse144893_search_data'); // allow logged in users | |
function wpse144893_search_data(){ | |
$errors = array(); | |
$data = array( | |
'status' => 'error', | |
'message' => '', | |
'result' => array() | |
); | |
if(!isset($_REQUEST['term']) || empty($_REQUEST['term'])) | |
$errors[] = 'No search term given!'; | |
if(!isset($_REQUEST['limit']) || empty($_REQUEST['limit'])) | |
$limit = 10; | |
else | |
$limit = (int) $_REQUEST['limit']; | |
if(empty($errors)){ | |
$term = sanitize_text_field($_REQUEST['term']); | |
// setup query data | |
$args = array( | |
'posts_per_page' => $limit, | |
's' => $term | |
); | |
$query = new WP_Query($args); // run query | |
$results = array(); | |
if($query->have_posts()): while($query->have_posts()): $query->the_post(); | |
$post_item = array( | |
'title' => get_the_title(), | |
'excerpt' => get_the_excerpt(), | |
'permalink' => get_permalink() | |
); | |
$results[] = $post_item; | |
endwhile; | |
$data['status'] = 'success'; | |
$data['message'] = 'Results found!'; | |
$data['result'] = $results; | |
else: | |
$errors[] = 'No post found!'; | |
$data['message'] = $errors; | |
endif; | |
} | |
echo json_encode($data); // print json | |
die(); // kill the script | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment