2015-04-03 58 views
0

我在一个WordPress的网站上有一个函数,它有一个互动的SVG地图,如果一个特定的国家有任何链接到它(通过posts2posts插件)然后这反映在地图本身。Wordpress - 通过悬停的Ajax从类别中提取帖子?

我希望做的事情是,如果用户悬停在地图的某个部分上,我们可以从该ID拉入帖子 - 如果这样做有道理?

因此,地图的每个部分都有自己的ID与帖子链接,我正在寻找一种方式,我可以查询该ID下的帖子,通过ajax将其拉入并显示给用户。

如果任何人都可以指出我正确的方向,那将是非常感谢!

+1

看一看http://wp-api.org/#posts_retrieve-a - 邮件。首先你需要安装它然后你可以使用它。 – jewelhuq 2015-04-03 22:13:06

+0

您可以使用[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

回答

1

挂钩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'); 
+0

谢谢戴夫!这看起来相当稳固,只需要一试,然后我会报告并标记答案,因为答案应该在正确的轨道上! :) – 2015-04-04 10:33:27

相关问题