2

So i'm trying to make a follow button in wordpress where users can press a button that allows them to follow an author they like. (No, i'm not interested in buddypress)

What i've done so far is use the code from Jon Masterson's Post Like System for WordPress http://hofmannsven.com/2013/laboratory/wordpress-post-like-system/ which pretty much adds a +1 update_post_meta when ever a user likes the post.

The problem i've ran into, is if you go all the way to the bottom you'll see that the like system uses update_post_meta to give a +1 to the count of the post meta, which is exactly what I need for the follow button. The problem is that I can't find a function update_author_meta to store the ++$author_follow_count for that specific author. If you know of a way for me to store and update the follow count for a specific author, or point me in the right direction, it would be greatly appreciated.

<?php
function follow_scripts() {
wp_localize_script( 'jk_like_post', 'ajax_var', array(
    'url' => admin_url( 'admin-ajax.php' ),
    'nonce' => wp_create_nonce( 'ajax-nonce' )
        )
    );
}
add_action( 'init', 'follow_scripts' );

/**
* (2) Save follow data
*/
add_action( 'wp_ajax_nopriv_jk-author-follow', 'jk_author_follow' );
add_action( 'wp_ajax_jk-author-follow', 'jk_author_follow' );
function jk_author_follow() {
   $nonce = $_POST['nonce'];
if ( ! wp_verify_nonce( $nonce, 'ajax-nonce' ) )
        die ( 'Nope!' );

if ( isset( $_POST['jk_author_follow'] ) ) {

    $author_id = $_POST['author_id']; // author id
    $author_follow_count = get_author_meta( $author_id,        "_author_follow_count", true ); // author follow count

    if ( function_exists ( 'wp_cache_post_change' ) ) { // invalidate WP Super Cache if exists
                $GLOBALS["super_cache_enabled"]=1;
                wp_cache_post_change( $post_id );
    }

    if ( is_user_logged_in() ) { // user is logged in
        $user_id = get_current_user_id(); // current user
        $meta_AUTHORS = get_user_option( "_followed_authors", $user_id ); // author ids from user meta
        $meta_USERS = get_author_meta( $author_id, "_user_followed" ); //user ids from author meta
        $followed_AUTHORS = NULL; // setup array variable
        $followed_USERS = NULL; // setup array variable

        if ( count( $meta_Authors ) !=0 ) { // meta exists, set up values
            $followed_AUTHORS = $meta_AUTHORS;
        }

        if ( !is_array( $followed_AUTHORS ) )  // make array just in case
            $followed_AUTHORS = array();

        if ( count( $meta_USERS ) !=0 ) { // meta exists, set up values
            $followed_USERS = $meta_USERS[0];
        }

        if ( !is_array( $followed_USERS ) ) //make an array just in case
            $followed_USERS = array();

        $followed_AUTHORS['author-'.$author_id, "_user_followed"] = $author_id; // Add author id to user meta array
        $followed_USERS['user-'.$user_id] = $user_id; // add user id to author meta array
        $user_follows = count( $followed_AUTHORS ); // count user follows

 // *** Where the snag is ****
        if ( !AlreadyFollowed( $author_id ) ) { // follow the author
            update_post_meta( $author_id, "_user_followed", $followed_USERS ); // Add user ID to author meta
            update_post_meta( $author_id, "_author_follow_count", ++$author_follow_count ); // +1 count author meta
            update_user_option( $user_id, "_followed_authors", $followed_Authors ); // Add author ID to user meta
            update_user_option( $author_id, "_author_follow_count", $user_follows ); // +1 count user meta
            echo $author_follow_count; // update count on front end

Update

Okay I fiddled with (4) and used your code. For some reason the default follower count is still 1. Also where do I place the die for the ajax? Thanks

/**
* (1) Enqueue scripts for follow system
*/
function follow_scripts() {
wp_enqueue_script( 'jk_follow_post', get_template_directory_uri().'/js/post-   like.min.js', array('jquery'), '1.0', 1 );
 wp_localize_script( 'jk_like_post', 'ajax_var', array(
    'url' => admin_url( 'admin-ajax.php' ),
    'nonce' => wp_create_nonce( 'ajax-nonce' )
        )
    );
}
/**
* (2) Save follow data
*/
add_action( 'wp_ajax_nopriv_jk-author-follow', 'jk_author_follow' );
add_action( 'wp_ajax_jk-author-follow', 'jk_author_follow' );
function jk_author_follow() {
$nonce = $_POST['nonce'];
if ( ! wp_verify_nonce( $nonce, 'ajax-nonce' ) )
        die ( 'Nope!' );

if ( isset( $_POST['jk_author_follow'] ) ) {

    $author_id = $_POST['author_id']; // author id


    if ( is_user_logged_in() ) { // user is logged in
        $user_id = get_current_user_id(); // current user

        // create the term if it doesn't exist
        if ( !term_exists( $author_id, 'wpse_180398_followers' ) ) {
            wp_insert_term( $author_id, 'wpse_180398_followers' );
        }

        // follow the user, note the last argument is true
        $term_ids = wp_set_object_terms( $user_id, $author_id, 'wpse_180398_followers', true );

        if ( is_wp_error( $term_ids ) ) {
            // There was an error somewhere and the terms couldn't be set.
            echo "error";
        } else {
            // Success!
        }
    }
}
}
/**
 * (3) Test if user already liked post
 */
function AlreadyFollowed( $author_id ) { // test if user is following author
$user_id = get_current_user_id(); // current user
$author_id = $_POST['author_id']; // author id
if ( is_user_logged_in() ) { // user is logged in
    if ( has_term( $author_id, 'wpse_180398_followers', $user_id ) ) {
        // user_id is following author_id!
    }
}
}
/**
  * (4) Front end button
*/
function getFollowLink( $author_id ) {
$following = '';
$author_id = get_query_var('author');
$user_id = get_current_user_id(); // current user
if (has_term( $author_id, 'wpse_180398_followers', $user_id )) {
    $following = ' following';
}
echo '<a class="follow-button' .$following. '" data-author="' .$author_id.  '">Follow</a>';
}
/**
 * (5) Add a shortcode to your posts instead
 * type [jkfollower] in your post to output the button
*/
function jk_follow_shortcode() {
return getFollowLink( get_the_ID() );
}
add_shortcode('jkfollower', 'jk_follow_shortcode');

Another Problem

I manually executed the code below just to see if the count is affected, and for some reason it's not, and just stays at 1.

$user_id = 1;
$author_id = 118;
wp_set_object_terms( $user_id, $author_id, 'wpse_180398_followers', true );
6
  • If an Author is an User, then you can use the update_user_meta() function to update a specific user meta -> codex.wordpress.org/Function_Reference/update_user_meta
    – gdaniel
    Mar 6, 2015 at 18:58
  • perfect! That's just what I needed
    – Julian
    Mar 6, 2015 at 19:03
  • You've muddled up AlreadyLiked and AlreadyFollowed, and you don't return a value in that function either. You also need to call die at the end of an AJAX callback. I wouldn't base it on the WP Like code either
    – Tom J Nowell
    Mar 6, 2015 at 22:03
  • Yeah I understand, I was trying to use it as a skeleton. I'll try and do what you posted
    – Julian
    Mar 6, 2015 at 22:16
  • the update ensues
    – Julian
    Mar 6, 2015 at 22:42

1 Answer 1

11

I would advise you not to use the user meta. Although your problem is caused by:

update_post_meta( $author_id, "_user_followed", $followed_USERS ); // Add user ID to author meta
update_post_meta( $author_id, "_author_follow_count", ++$author_follow_count );

note that you called update_post_meta not update_user_meta, so somewhere, there's a post whose ID is the same as the user ID of the author, that's getting strange post meta added.

However, it's still an inefficient method, and prone to race conditions that might give inaccurate counts. You're also going to have a very costly piece of code when trying to figure out who follows an author because you'll have to check each and every single user to see if they follow that author.

Instead, use a custom taxonomy.

Using a Custom User Taxonomy

Taxonomies aren't just for posts. In this taxonomy, terms are authors, and the objects being tagged are users ( specifically we're using User IDs as our slugs ).

Assuming we call this taxonomy wpse_180398_followers, to follow an author:

// follow the user, note the last argument is true
$term_ids = wp_set_object_terms( $user_id, $author_id, 'wpse_180398_followers', true );

if ( is_wp_error( $term_ids ) ) {
    // There was an error somewhere and the terms couldn't be set.
} else {
    // Success!
}

To unfollow someone:

wp_remove_object_terms( $user_id, $author_id, 'wpse_180398_followers' );

To check if a user is following an author:

if ( has_term( $author_id, 'wpse_180398_followers', $user_id ) ) {
    // user_id is following author_id!
}

To get the followers of an author:

$followers = get_objects_in_term( $author_id, 'wpse_180398_followers' );

To get an authors follower count:

count( $followers );

To get the authors a user follows:

$author_terms = wp_get_object_terms( $user_id, 'wpse_180398_followers' );
foreach ( $author_terms as $term ) {
    echo $term->slug; // the slug is the author ID
}

Further advantages:

  • These are the same APIs used for categories and tags, they'll be significantly faster than using user meta
  • No race conditions on term counts
  • Term counts are cached sometimes
  • You'll have a taxonomy, which means archive templates for each term and a URL structure for free!

You'll want your taxonomy to be non-hierarchical, you'll probably want to change the prefix on the name I gave it to something more unique to you ( don't just call it followers ), and if you want a user interface in the admin interface you'll want to read this

The only other note is you may want to delete the term associated with a user when they're deleted. To delete the term or remove all of a users followers:

wp_delete_term( $author_id, 'wpse_180398_followers' );

To reset who a user follows to nobody:

wp_delete_object_term_relationships( $user_id, 'wpse_180398_followers' );

Tips for The Button Itself

As you already have an AJAX endpoint in your question, you can remove most of the code inside it and replace it with the snippets above. As for the button, you'll want an element:

<a class="follow-button">Follow</a>

That's also a toggle, so it'll need something to indicate if you're already following or not:

<a class="follow-button following">Follow</a>

Of course if it's got the following class, change how it looks like when you see a twitter follow button. You'll only want the following class if you're actually following the person though:

<?php
$following = '';
if ( has_term.. etc as above ) {
    $following = ' following';
}
?>
<a class="follow-button<?php echo $following; ?>">Follow</a>

And of course it needs the ID of the author somehow, lets use a data attribute:

<?php
$following = '';
if ( has_term.. etc as above ) {
    $following = ' following';
}
?>
<a class="follow-button<?php echo $following; ?>" data-author="<?php echo $author_id; ?>">Follow</a>

I trust you know how to get the authors ID based on your question.

Finally, you'll want some javascript so that when a user clicks on a follow button ( jQuery( 'a.follow-button').click, it:

  • checks if the element has the following class
  • If it does, it fires an AJAX to unfollow the author
  • If it doesn't, it fires an AJAX to follow the author
  • It passes the author data value of the element ( .data( 'author' ) in jQuery )
  • It toggles the following class on the element so that the user gets some feedback ( .toggle('following') )
  • Bonus points for adding an follow-in-progress class that adds a spinner in css and makes the javascript bail out if it's picked up so you don't duplicate the requests
5
  • thanks for everything, do you think you could point me in the right direction for creating a simple button to execute the function?
    – Julian
    Mar 6, 2015 at 20:14
  • You already have an AJAX endpoint, take the code inside the function out and rebuild it using the snippets in my answer, the button itself is just a javascript task to implement a toggle
    – Tom J Nowell
    Mar 6, 2015 at 20:15
  • Updated with a section to help implement the button, I recommend you read the AJAX API docs for how to set up the AJAX request itself
    – Tom J Nowell
    Mar 6, 2015 at 20:26
  • I've also simplified following a user and added one or two more actions ( unfollowing every author )
    – Tom J Nowell
    Mar 6, 2015 at 20:33
  • I updated my progress
    – Julian
    Mar 6, 2015 at 21:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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