Wordpress - 在Hover上通过Ajax从类别中提取帖子?

时间:2015-04-03 21:40:39

标签: php jquery ajax wordpress

我在wordpress网站上有一个功能,我现在正在工作,它有一个交互式SVG地图,如果一个特定国家有任何链接到它(通过posts2posts插件)然后这反映在地图上本身。

我希望做的是,如果用户悬停在地图的某个部分上,我们可以从该ID中提取帖子 - 如果这有意义的话?

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

如果有人能指出我正确的方向,我们将不胜感激!

1 个答案:

答案 0 :(得分: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' );