Wordpress-通过悬停上的Ajax从类别中提取帖子


Wordpress - Pull posts from category via Ajax on Hover?

我目前正在开发的wordpress网站中有一个函数,它有一个交互式SVG地图,如果某个特定国家有任何链接(通过posts2posts插件),那么这会反映在地图本身上。

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

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

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

钩子wp_ajax确实是您想要的。我在下面创建了一个(未经测试的)示例。如果你打算使用这个,请确保稍后添加nonces。WordPress、AJAX和nonces的基本教程可以在这里找到。

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' );