I'm working on my first plugin. I would like to add a follow button for the posts, so the logged in users can follow the authors.

I placed the following lines into functions.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) {
    var userID = $(this).attr('href').slice(1);

            type: "GET",
            url: "index.php",
            data: 'userID='+userID,
            success: function(msg){


After I click to the follow button I see on the net tab: index.php?userID=X, but nothing happens in the database. Where is the problem?

  • I think the problem is with the if(is_numeric($userID)) { part. – Tina88 Jun 29 '14 at 9:15
  • An earlier question about AJAX in plugins prompted me to do a write-up with a working example. This might help: willthewebmechanic.com/… – Will Jun 29 '14 at 11:42

You're not using wordpress default ajax mechanism.

To do that:

  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) {

AJAX Request Handler

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

You can Refer Wordpress Codex. http://codex.wordpress.org/AJAX_in_Plugins. It's pretty well documented.

Here's already answer question to your problem. i.e. https://stackoverflow.com/questions/17855846/using-ajax-in-a-wordpress-plugin

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.