I have a world map on a WordPress page. I’d like to load a particular post onto the page depending on what region of the map is clicked. I’m writing this as a plugin for my site. Here is what I have now:
index.php:
function get_post_data(){
// Switch based on region
switch($_REQUEST['region']) {
//Asia
case 'China':
case 'Japan':
class Post{
function get_post(){
global $more;
$more = 0;
query_posts('p=122');
if(have_posts()) : while(have_posts()) : the_post();
the_title( '<h2>', '</h2>' );
the_post_thumbnail('medium');
the_content( '<p>', '</p>' );
endwhile;
endif;
wp_reset_query();
}
}
break;
//Middle East
case 'Pakistan':
case 'Afghanistan':
class Post{
function get_post(){
global $more;
$more = 0;
query_posts('p=123');
if(have_posts()) : while(have_posts()) : the_post();
the_title( '<h2>', '</h2>' );
the_post_thumbnail('medium');
the_content( '<p>', '</p>' );
endwhile;
endif;
wp_reset_query();
}
}
break;
//etc
}
$post = new Post();
$post->get_post();
echo json_encode($post);
die();
}
add_action('wp_ajax_get_post_data', 'get_post_data');
add_action('wp_ajax_nopriv_get_post_data', 'get_post_data');
?>
start.js:
onRegionClick: function(element, code, region)
{
$.ajax(get_data.ajaxurl, {
data: {region: region, 'action': 'get_post_data'},
dataType: 'json',
success: function(response) {
$("#post").html(response);
}
});
}
the AJAX response is returning all of the markup related to the posts I want, but itâs not outputting it to the #post div. So I know the AJAX, the switch, and the map are set up properly. I just don’t know how to assign a WP post to a variable that I can then output in JSON. I think it has something to do with get_the_content() but Iâm not sure how to properly use thatâ¦.
Revise the following and it should work:
Don’t use
query_posts
. For this kind of query,get_posts()
is the good one. But as you’re pulling just one post, thenget_post()
is enough.You’re duplicating the declaration of your class and buried inside a switch. It should go to the root and pass the post ID to the custom method
get_post( $ID )
.It would be something like this (untested):