如何使用AJAX和WordPress?

时间:2014-06-29 作者:Tina88

我正在开发我的第一个插件。我想为帖子添加一个关注按钮,这样登录的用户就可以关注作者了。

我将以下几行放入函数中。php

function add_query_vars_filter( $vars ){
       $vars[] = "userID";
       return $vars;
  }
add_filter( \'query_vars\', \'add_query_vars_filter\' );

// The code to display the button
function show_follow_button() {
    $author_ID = get_the_author_meta(\'ID\');
    $current_user = wp_get_current_user();
    if ( is_user_logged_in() && $current_user->ID != $author_ID ) {
        return \'<a href="#\'.$author_ID.\'" title="" class="follow-user">Follow</a>\';
    }
}

// The update function, I know I have to use array for the ids, it\'s for only test
$userID = (get_query_var(\'userID\')) ? get_query_var(\'userID\') : false;

if(is_numeric($userID)) {
    $current_user = wp_get_current_user();
    update_user_meta($current_user->ID, \'following\', $userID);
}

// jQuery
$(\'.follow-user\').click(function(e) {
    e.preventDefault();
    var userID = $(this).attr(\'href\').slice(1);
    $.ajax({

            type: "GET",
            url: "index.php",
            data: \'userID=\'+userID,
            success: function(msg){
                $(\'.follow-user\').html(\'Followed\');
            }

        });
});
单击“跟随”按钮后,我在“网络”选项卡上看到:索引。php?userID=X,但数据库中什么都没有发生。问题出在哪里?

1 个回复
SO网友:Abhineet Verma

您没有使用wordpress默认的ajax机制。

为此:

jQuery.ajax({
  type: "POST",
  url: "/wp-admin/admin-ajax.php", // Send request to admin-ajax.php
  data: newcontact, // Can be anything. As per your need
  action: \'myaction\', // Required to send otherwise Wordpress AJAX won\'t authorize your request.
  success: function(data) {
    jQuery(".follow-user").html(data);
  }
});
AJAX请求处理程序
add_action( \'wp_ajax_myaction\', \'so_wp_ajax_function\' );
add_action( \'wp_ajax_nopriv_myaction\' \'so_wp_ajax_function\' );
function so_wp_ajax_function(){
  //DO whatever you want with data posted
  //To send back a response you have to echo the result!
  echo $_POST[\'name\'];
  echo $_POST[\'age\'];
  wp_die(); // ajax call must die to avoid trailing 0 in your response
}
你可以参考Wordpress Codex。http://codex.wordpress.org/AJAX_in_Plugins. 有很好的记录。

这已经是你问题的答案了。i、 e。https://stackoverflow.com/questions/17855846/using-ajax-in-a-wordpress-plugin

结束

相关推荐