首先,一些推荐阅读-AJAX in Plugins.
我意识到这不是一个插件,但Codex仍然是相关的,正如您将在PHP部分中看到的,您可以使用WP AJAX处理程序来处理前端调用以及来自管理区域的调用。
为此,最好将JS放在外部*。页面中包含的js文件。这样,您就可以只拥有一块代码,而不是对循环中的每个帖子重复它。
要捕获mouseenter 其中任何一项的事件<divs> 我们可以添加一个类(请参见PHP 然后在发出AJAX请求之前获取ID。
你会注意到在我前面提到的段落中mouseenter, 不mouseover; 这是因为mouseenter 每次访客悬停在<div>, 其中为mouveover 每次移动鼠标时都会重复发射。
jQuery(document).ready(function($){
    $(\'.update-hover-count\').on(\'mouseenter\', function(){
    
        var data = {
            action:     \'update_hover_count\',                   // The AJAX action to carry out
            post_id:    $(this).attr(\'id\').replace(/\\D/g, \'\')   // The numerical ID of the post that has been hovered
        }
        
        /** Make the AJAX request */
        $.post(MyAjax.ajaxurl, data, function(response){
        
            // This is the success function, do somthing here if you wish but you don\'t have to.
            
        }).fail(function(){
        
            // Do something to log a failure, if you wish but you don\'t have to.
            
        });
        
    });
    
});
 使用内置WordPress AJAX处理程序时(
wp-admin/admin-ajax.php) WP的所有优点都可用于AJAX调用。这也意味着您不必为AJAX例程创建独立的文件,您可以将其添加到
functions.php 它是通过一个钩子调用的(尽管您仍然可以将其保存在自己的文件中,并根据需要将其包含在该文件中)。
由于这将(我假设)在前端,您必须将上述内容本地化admin-ajax.php 脚本,使其可用,但也可以添加到functions.php
/**
 * Localize the admin-ajax script
 */
add_action(\'wp_enqueue_scripts\', \'my_localize_ajax_admin\');
function my_localize_ajax_admin(){
    /** For AJAX requests */
    wp_enqueue_script(\'my-ajax-request\', admin_url(\'admin-ajax.php\'), array(\'jquery\'));
    wp_localize_script(\'my-ajax-request\', \'MyAjax\', array(\'ajaxurl\' => admin_url(\'admin-ajax.php\')));
    
}
/**
 * AJAX call to update the number of times a post is hovered
 */
add_action(\'wp_ajax_update_hover_count\', \'my_update_hover_count\');          // For users who are logged in
add_action(\'wp_ajax_nopriv_update_hover_count\', \'my_update_hover_count\');   // For users who are NOT logged in
function my_update_hover_count(){
    $post_id = $_POST[\'post_id\'];   // Extract the ID of the post that was hovered
    
    /** Grab the postmeta value for \'hits\' for \'post_id\' */
    $key = \'hits\';
    $hits = get_post_meta($post_id, $key, TRUE);
    
    /** Check to see if any hits have been previously recoreded */
    if($hits) : // They have, update the postmeta key
        $new_hits = intval($hits + 1);
        update_post_meta($post_id, $key, $new_hits, $hits);
    else :  // They have not, create the postmeta key
        add_post_meta($post_id, $key, 1);
    endif;
    
    echo get_post_meta($post_id, $key, TRUE);
    
    die();  // Required for a proper result
    
}
 现在,处理AJAX调用的脚本位于*。js文件,模板文件中的HTML使用AJAX例程要简单得多。
<div id="post-<?php the_ID() ?>" <?php post_class(\'update-hover-count\'); ?>>
    <!-- Add additional HTML here -->
    
</div>