挂钩wp_ajax确实是你在找什么。我在下面创建了一个(未经测试的)示例。如果你打算使用这个,确保稍后添加随机数。 WordPress,AJAX和noncens的基本教程可以在here找到。
mapinfo.js(模板目录)
// Create variable
var mapID;
// Document ready
jQuery(document).ready(function($) {
// Hover over the element
$('.map_section').mouseenter(function(){
// Get hovered element map ID and save it in the mapID variable
mapID = $(this).attr('ID');
// JSON request: use the url from the localized script and use the get_map_info function. Both created in functions.php
$.post(mapAjax.ajaxurl, {
action: 'get_map_info',
mapID: mapID
}, function(response) {
// Turn the response into JSON variable called data
var data = getJSON(response);
/* Do whatever you want with the data here */
$('#'+mapID).html(data.content);
// Console.log the data for debugging
console.log(data);
});
});
});
的functions.php
// Localize the scripts so you have access to the AJAX variables in the front-end.
function enqueue_map_scripts(){
// Enqueue your custom 'mapinfo.js' script
wp_enqueue_script('mapinfo', get_template_directory_uri().'/mapinfo.js', array('jquery'), null, true);
// Localize this script to get the ajaxurl variable in the frontend
wp_localize_script('mapinfo', 'mapAjax', array('ajaxurl' => admin_url('admin-ajax.php')));
}
add_action('admin_enqueue_scripts', 'enqueue_map_scripts');
// The function for getting the map info
function get_map_info(){
// Get the map ID from the AJAX-request
$mapID = $_POST['mapID'];
// Create an array to store the map information
$mapInfo = array();
// Get title, content and a meta field, add it to the mapInfo array
$mapInfo['title'] = get_the_title($mapID);
$mapInfo['content'] = get_the_content($mapID);
$mapInfo['meta'] = get_post_meta($mapID, '_example_meta_field', true);
// Send JSON
echo json_encode($mapInfo);
// Die
exit();
}
add_action('wp_ajax_get_map_info', 'get_map_info');
add_action('wp_ajax_nopriv_get_map_info', 'get_map_info');
看一看http://wp-api.org/#posts_retrieve-a - 邮件。首先你需要安装它然后你可以使用它。 – jewelhuq 2015-04-03 22:13:06
您可以使用[wp_ajax](https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_%28action%29)通过ajax查询Wordpress。还可以查看[插件中的AJAX](https://codex.wordpress.org/AJAX_in_Plugins)获取更多资源。 – d79 2015-04-03 23:41:31