Last active
January 4, 2016 12:49
-
-
Save petenelson/8623790 to your computer and use it in GitHub Desktop.
WordPress: AJAX action to return posts by taxonomy term
This file contains hidden or 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: GGA - AJAX Posts by Taxonomy | |
Author: Pete Nelson (@GunGeekATX) | |
Description: <a href="http://petenelson.com/wp-admin/admin-ajax.php?action=gga_posts_by_taxonomy&post_type=post&taxonomy=post_tag&term=android">Try it out</a> | |
Version: 1.0 | |
*/ | |
/* | |
http://petenelson.com/wp-admin/admin-ajax.php?action=gga_posts_by_taxonomy&post_type=post&taxonomy=post_tag&term=android | |
*/ | |
add_action('wp_ajax_gga_posts_by_taxonomy', 'gga_posts_by_taxonomy'); | |
add_action('wp_ajax_nopriv_gga_posts_by_taxonomy', 'gga_posts_by_taxonomy'); | |
function gga_posts_by_taxonomy() { | |
$results = new stdClass(); | |
$results->posts = array(); | |
$post_type = isset($_REQUEST['post_type']) ? $_REQUEST['post_type'] : ''; | |
$taxonomy = isset($_REQUEST['taxonomy']) ? $_REQUEST['taxonomy'] : ''; | |
$taxonomy_term = isset($_REQUEST['term']) ? $_REQUEST['term'] : ''; | |
if (empty($post_type)) | |
$post_type == 'post'; | |
$query_args = array( | |
'post_type' => $post_type, | |
'posts_per_page' => -1, | |
); | |
if (!empty($taxonomy) && !empty($taxonomy_term)) { | |
$query_args['tax_query'] = array( | |
array( | |
'taxonomy' => $taxonomy, | |
'field' => 'slug', | |
'terms' => $taxonomy_term, | |
) | |
); | |
} | |
global $post; | |
$query = new WP_Query($query_args); | |
while ($query->have_posts()) { | |
$query->the_post(); | |
$results->posts[] = array( | |
'id' => $post->ID, | |
'permalink' => get_permalink( $post->ID ), | |
'post_title' => get_the_title( $post->ID ), | |
'post_name' => $post->post_name | |
); | |
} | |
wp_reset_query(); | |
header('Content-Type: application/json'); | |
echo json_encode($results); | |
die(); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment