2015-04-03 1 views
0

У меня есть функция на сайте wordpress, над которой я работаю в данный момент, с интерактивной SVG-картой. Если у конкретной страны есть что-то связанное с ней (через плагин posts2posts), то это отражается на самой карте.Wordpress - Вытягивать сообщения из категории через Ajax на Hover?

Что я надеюсь сделать, так это то, что если пользователь навешивается над разделом карты, мы можем потянуть за столбики с этого идентификатора - если это имеет смысл?

Таким образом, каждый раздел карты имеет свой собственный идентификатор с сообщениями, связанными, я ищу способ, которым я мог бы запрашивать сообщения под этим идентификатором, втягивать их через ajax и отображать их пользователю.

Если кто-то может указать мне в правильном направлении, это было бы очень признательно!

+1

Посмотрите http://wp-api.org/#posts_retrieve-a -после . Сначала вам нужно установить его, затем вы можете его использовать. – jewelhuq

+0

Вы можете использовать [wp_ajax] (https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_%28action%29) для запроса Wordpress через ajax. Также ознакомьтесь с [AJAX в плагинах] (https://codex.wordpress.org/AJAX_in_Plugins) для получения дополнительных ресурсов. – d79

ответ

1

Крючок wp_ajax действительно то, что вы ищете. Я создал (непроверенный) пример ниже. Если вы собираетесь использовать это, обязательно добавьте nonces позже. Основной учебник для 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

Спасибо Дэйв! Это выглядит довольно солидно, вот-вот дать ему пробег, и я отчитаю и отметю ответ как ответ, если мы будем на правильном пути! :) –