Created
April 10, 2012 13:29
-
-
Save PhilKershaw/2351382 to your computer and use it in GitHub Desktop.
WordPress Post term list via AJAX
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 | |
/* | |
* A demo function to compile a list of locations (WordPress Terms) based on a 'type' (also WordPress Terms: 'commercial', 'residential', 'land'). Requested and returned via AJAX. | |
* | |
* @author Phil Kershaw | |
*/ | |
add_action('wp_ajax_get_locations', 'get_locations'); | |
add_action('wp_ajax_nopriv_get_locations', 'get_locations'); | |
function get_locations() | |
{ | |
global $wpdb; | |
$type = $_POST['type']; | |
$query = " SELECT DISTINCT SQL_CALC_FOUND_ROWS wp_posts.ID | |
FROM wp_posts | |
INNER JOIN wp_term_relationships | |
ON (wp_posts.ID = wp_term_relationships.object_id) | |
INNER JOIN wp_term_taxonomy | |
ON wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id | |
INNER JOIN wp_terms | |
ON wp_term_taxonomy.term_id = wp_terms.term_id | |
WHERE (wp_posts.post_type = 'sale') | |
AND (wp_posts.post_status = 'publish') | |
AND (wp_terms.slug = '$type')"; | |
$ids = $wpdb->get_results($wpdb->prepare($query)); | |
foreach($ids as $id) | |
{ | |
$terms = wp_get_post_terms($id->ID, 'location'); | |
foreach($terms as $term) | |
{ | |
foreach($locations as $index => $location) | |
{ | |
$match = false; | |
if ($location['slug'] == $term->slug) | |
{ | |
$locations[$index]['total']++; | |
$match = true; | |
break; | |
} | |
} | |
if ($match != true) | |
{ | |
$locations[] = array( | |
'name' => $term->name, | |
'slug' => $term->slug, | |
'total' => 1 | |
); | |
} | |
} | |
} | |
sort($locations); | |
die(json_encode($locations)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment