2015-04-03 62 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

相關問題