On my WordPress website, I'm writing a plugin with a world map that loads a particular post depending on what region is clicked using AJAX. I'd like to include links within the main navigation that point to the map page with a region's post already displayed (ex: the link titled "Middle East" would direct the user to the map page with the Middle East post already displayed). I'm trying to use location.hash but I don't totally understand how it works. Here is my code:
start.js:
jQuery(document).ready(function() {
// Added code based on jetlej's answer
jQuery('#vmap').ready( function(event, code, region) {
$.ajax(get_data.ajaxurl, {
data: {region: region, 'action': 'get_post_data'},
dataType: 'json',
success: function(response) {
$("#post").html(response);
location.hash = region;
}
});
});
jQuery('#vmap').vectorMap({
map: 'world_en',
backgroundColor: '#fff',
// more map config options...
onRegionClick: function(element, code, region)
{
if (location.hash) {
location.hash.replace("#","")+".html"
}
$.ajax(get_data.ajaxurl, {
data: {region: region, 'action': 'get_post_data'},
dataType: 'json',
success: function(response) {
$("#post").html(response);
location.hash = region;
}
});
}
});
});
index.php:
class Post{
function get_post( $ID ){
$html = '';
$post = get_post( $ID );
if( $post ) {
$html = $post->post_title;
$html .= wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'medium' );
$html .= $post->post_content;
}
return $html;
}
}
function get_post_data(){
$post = new Post();
$result = '';
// Swtich based on region
switch($_REQUEST['region']) {
//Europe
case 'Russia':
case 'Albania':
$result = $post->get_post( 405 );
break;
//Africa
case 'Congo':
case 'Nigeria':
$result = $post->get_post( 388 );
break;
echo json_encode($result);
die();
}
add_action('wp_ajax_get_post_data', 'get_post_data');
add_action('wp_ajax_nopriv_get_post_data', 'get_post_data');
And my links look like this:
<a href="http://example.com/where-we-serve/#Russia">Europe</a>
When I click the link, it takes me to the map page but it's in its default state with no posts displayed. I'm getting the hash values in the URL when I click the map, but they don't seem to actually have any effect on the state of the page. Is this an issue with how I'm using location.hash, an issue with the link, or is this just the wrong approach?