In this final part of the User Follow System tutorial series, we will create two short codes, one for displaying a follow/unfollow link for a user and one for displaying a list of recent posts from users you (the currently logged-in user) follow. We will wrap up the series by also showing a few areas the plugin could be improved to create a more complete plugin.

The first short code we will write is the one to output the follow / unfollow links.

In one of the previous parts, we wrote a function called pwuf_get_follow_unfollow_links(), which allows us to retrieve the follow / unfollow links for a specific user. Our short code, which we will call [follow_links], will simply be a wrapper of this function. Go ahead and open includes/shortcodes.php and place the following in it:

/**
 * Shows the links to follow/unfollow a user
 *
 * @access      private
 * @since       1.0
 * @return      string
 */
 
function pwuf_follow_links_shortcode( $atts, $content = null ) {
 
	extract( shortcode_atts( array(
			'follow_id' => get_the_author_meta( 'ID' )
		),
		$atts, 'follow_links' )
	);
 
	return pwuf_get_follow_unfollow_links( $follow_id );
}
add_shortcode( 'follow_links', 'pwuf_follow_links_shortcode' );

This short code is really quite simple. The first thing we do is allow the site admin to pass an attribute to the short code called follow_id. This is the user ID we want to output follow / unfollow links for. If the attribute is left blank, we default to retrieving the author ID of the current post.

Once we are finished retrieving the short code attributes, we simply return the pwuf_get_follow_unfollow_links() function (note that we have passed in $follow_id).

That’s it for our first short code. If you place it on a page or post and then view that post or page while logged into another user account (cannot be the same as the post author), you will see the follow link and it will be fully functional.

Now lets write our short code that displays recent posts published from the users we follow. This short code is a little more complex, but still pretty simple, thanks to the helper functions we wrote in the previous parts of this series.

We will start with a shell function:

/**
 * Shows the posts from users that the current user follows
 *
 * @access      private
 * @since       1.0
 * @return      string
 */
 
function pwuf_following_posts_shortcode( $atts, $content = null ) {
 
	// Make sure the current user follows someone
	if( empty( pwuf_get_following() ) )
		return;
 
	$items = new WP_Query( array(
		'post_type'      => 'any',
		'posts_per_page' => 15,
		'author__in'     => pwuf_get_following()
	) );
 
	ob_start();
 
       // output will go here.
 
	return ob_get_clean();
 
}
add_shortcode( 'following_posts', 'pwuf_following_posts_shortcode' );

We are doing a few things here:

1. We check to ensure the current user is following at least one user.

2. We setup a WP_Query to retrieve items from users we follow. Notice that we pass pwuf_get_following() to the author__in parameter. This parameter expects an array of user IDs, which is exactly what pwuf_get_following() gives back to us.

3. We setup an output buffer, which is where we will create the actual output of the short code.

The output will be a simple unordered lists of post titles linked to their respective single views.

Here’s the complete short code:

/**
 * Shows the posts from users that the current user follows
 *
 * @access      private
 * @since       1.0
 * @return      string
 */
 
function pwuf_following_posts_shortcode( $atts, $content = null ) {
 
	// Make sure the current user follows someone
	if( empty( pwuf_get_following() ) )
		return;
 
	$items = new WP_Query( array(
		'post_type'      => 'any',
		'posts_per_page' => 15,
		'author__in'     => pwuf_get_following()
	) );
 
	ob_start(); ?>
<ul>
<ul><?php if( $items->have_posts() ) : ?> <?php while( $items->have_posts() ) : $items->the_post(); ?>
	<li class="pwuf_following_post"><?php the_title(); ?></li>
</ul>
</ul>
<?php endwhile; ?> <?php wp_reset_postdata(); ?> <?php else : ?>
<ul>
<ul>
	<li class="pwuf_following_post pwuf_following_no_results"><?php _e( 'None of the users you follow have posted anything.', 'pwuf' ); ?></li>
</ul>
</ul>
<?php endif;
	return ob_get_clean();
 
}
add_shortcode( 'following_posts', 'pwuf_following_posts_shortcode' );

The way we are using WP_Query in this short code is pretty standard, so I won’t go into an explanation of everything in the post loop, but feel free to ask questions if you are unsure of any part of it.

We now have two fully functional short codes, and with that our plugin is complete! Users can be followed, unfollowed, and recent items from users you follow can be viewed. We have also laid the ground work for a much larger set of functionality, such as incorporating a follow system into a site like CG Cookie.com

Though our plugin is complete, there are still several areas it could be improved.

1. We could add options to [following_posts] short code to determe the number of items displayed, the post types items are pulled from, and even things like pagination support.

2. We could add a complete template file engine that would allow site owners to easily modify the output of the functions and short codes without ever modifying the core plugin.

The completed plugin can be downloaded below.

Download Plugin

  1. shubhra chaudhary

    I am thinking of 1 month paid membership only to download this plugin. It’s been a year since this tutorial was started, so I am a bit skeptical to join right now. When will the download be available?

    • Pippin

      The download is available in this part. Part 7 was the final piece.

  2. shubhra chaudhary

    Fatal Error: Can’t use function return value in write context in C:\wamp\www\wordpress1\wp-content\plugins\user-following-system\includes\shortcodes.php on line 47

    • Pippin

      Is that after following the tutorial series or simply downloading the final plugin?

  3. shubhra chaudhary

    That’s after downloading the final plugin folder. It gives the error when I try to activate the uploaded zip folder.

    • Pippin

      Try now.

  4. shubhra chaudhary

    Hi. Its working perfectly now. A few things I want to know. I am trying to make a format just like http://cgcookie.com/profile/ace00/.

    Here’s my code for the author template http://snippi.com/s/jij4aay. How do i get the ‘follow’ link in my template and the follower and following count?

    There’s another thing. The ‘following_posts’ shortcode is returning posts as well as pages. I only want posts & CPT. What needs to be altered?

    P.S. Thanks for the awesome tutorial. You are the best.

    • Pippin

      Please go through the entire tutorial step by step as it should answer all of those questions.

  5. Peter Hudson

    Thanks Pippin – much appreciated.

  6. Danniel Chiiko

    Thank you for the great tutorial. Please help me on the questions below;

    1. How do I get the number of users following a particular author. e.g 2,000 followers.
    2. Do you have plans for a tutorial on following categories?
    3. How do I create a button on the follow/unfollow button?
    4. Is it possible for followers to receive an email everytime the followed user publishes a post?

    • Pippin

      1. You can use the pwuf_get_following_count() and pwuf_get_follower_count() functions.

      2. No I do not.

      3. You will need to use CSS for that.

      4. Sure, you can attach a function to the “pwuf_post_follow_user” action to trigger an email.

  7. tommy80

    I’ve got a subscription, downloaded the plugin and put into operation and here are the problems encountered
    1 – FOLLOWING the count (pwuf_get_following_count) starts to count from 1 mind it should start from 0
    2 – I started to follow between users and some users who have not done any follow are found to have the same follow another person as if they were counted in the ‘following_count’ the follow another user when in fact it made ​​them … same thing in follower_count

    sorry for my english

    • Pippin

      1). Is it showing 1 even for users that have no followers?

      2). Sorry, I’m not sure I understand this question.

  8. tommy80

    1). Is it showing 1 even for users that have no followers?

    Yes

    2). Sorry, I’m not sure I understand this question.

    Example Problem:

    “utente111” has never been connected but finds himself following 5 users with 3 followers
    should really be follow= 0 and followers = 0.

    utente000 it is connected and has assets follow= 5 and followers = 3

    utente111 therefore has the same activity utente000
    but in reality it is not so
    is a bug?

    you understand?

    • tommy80

      but this plugin has been tested?

    • Pippin

      Did you follow the tutorial for how to create the plugin or just download the final results? Note that this series is designed to show you how to build it, not just to provide a final product.

      This plugin is in use extensively by CG Cookie.com

  9. tommy80

    I’m download the final results this plugin and then I used the functions pwuf_get_following_count () and pwuf_get_follower_count () to print Following and followers…

    Sorry Pippin but if I can download the plugin by entering into a paid subscription I saw that I paid I hope to find a product that works

    Sorry again for my english

    ps: Can you fix the bugs I listed? please

  10. Jay

    How do you retrieve or list all the followers/following by name, avatar etc instead of id?

  11. Peter Hudson

    Hi Pippin,

    Sorry to say i have the same problem for the counts. I think the problem is with the wya the arrays are initially created.

    As an example ——> function pwuf_follow_user( $user_id, $user_to_follow )

    It checks to see if the is a $following and if $following is an array.
    The problem is that when $following is returned, it is always returned as an array.
    It needs to check to see is the user meta is empty first and return nothing if it is.

    This causes two problems because whenever following is returned, it will always have at least a count of 1 (because although the first element in the array is empty – it will still be counted as one).

    Also, when you are adding the first follower or followed user Id to the array, it adds it as a second element in the array (the first one being the empty one you returned). this means everyone will always have a count of one if not following anyone, and will show one more user than they are actually following from the point they follow their first.
    I hope this makes sense?

    The simple way to fix this is to check to see if the user meta returned when getting the id’s of followed/followers is empty and return nothing if it is.

    So I used the following (and the same in pwuf_get_follower) , but you may have a neater way of doing this, I’m still learning.

    function pwuf_get_following( $user_id = 0 ) {
    if ( empty( $user_id ) ) {
    $user_id = get_current_user_id();
    }
    $following = get_user_meta( $user_id, ‘_pwuf_following’, true );

    //This is the bit I added that return nothing if $following is empty
    if (empty($following)) {
    return;
    }
    //to here

    return (array) apply_filters( ‘pwuf_get_following’, $following, $user_id );
    }

    I’m sorry if I shouldn’t post code – wasn’t sure how best to explain. I don’t know about the other problem tommy80 mentioned because I’m still just setting it up.

    • Pippin

      You’re absolutely right! Thanks for catching that! I will get an update out as soon as I can.

  12. tommy80

    Pippin please update the plugin as soon as possible!
    I waited for a year this plugin…
    I need it! Are still pending…

    • Pippin

      Please download it again now and let me know if that corrects the problem.

      Please, please note again that this plugin was designed as a tutorial, NOT just as a ready-to-download-and-use plugin. It is meant mostly for educational purposes to demonstrate how to do it.

  13. tommy80

    Thanks for the update
    Yeah I know that started as tutorial and you did a super job, congratulations
    but when the chance to download the plugin
    I think the plugn must be working and complete πŸ™‚

    thanks again for the update and hopefully good
    I’ll let you know if the problems have been solved

  14. tommy80

    I have tested with v1.0.1 and it does not work
    problem of users clones count Following and followers
    some do not even appear in the follow button
    In conclusion: for the moment the plugin can not be used

    • Pippin

      Can you show me screenshots of what you see?

      Also, please test with just the default Twenty Twelve theme to ensure there isn’t a conflict with your theme.

    • tommy80

      Pippin thanks for the plugin and for your help

  15. Peter Hudson

    Hi Pippin,

    First up – your welcome. I spotted that it was doing something weird, but it was a good learning experience working it through – it helped me understand the plug-in more πŸ™‚

    The tutorial in itself was excellent and I am delighted you finished it. I am thinking of other ways I might be able to use similar techniques. I noticed you used a similar method to this in your user bookmarks plug-in so its good to have both for reference.

    Many thanks.

    P.S I’m not noticing any more strange behavior – looking at the code I don’t see any way it could be counted incorrectly if set up properly. I was wondering if tommy80 has checked that he is passing the correct id’s in the follow/unfollow link function?

    So in your tutorial it says

    Where $user_id_to_follow is obviously the id of the user to be followed. Is the correct ID (or variable) being passed to the function by tommy80?

    • Peter Hudson

      Sorry realised I put the wrong bit of code in – I meant:

      pwuf_get_follow_unfollow_links( $user_id_to_follow )

  16. tommy80

    Hi Peter Hudson.

    My code:

    // start follow_unfollow user

    $follow_unfollow = pwuf_get_follow_unfollow_links( get_the_author_meta( ‘ID’ ) );

    echo $follow_unfollow;

    // start follow_unfollow user count FOLLOWING

    $following_count = pwuf_get_following_count( get_the_author_meta( ‘ID’ ) );

    echo $following_count. ‘following’;

    // start follow_unfollow user count FOLLOWER

    $follower_count = pwuf_get_follower_count( get_the_author_meta( ‘ID’ ) );

    echo $follower_count. ‘follower’;

    • Peter Hudson

      If I understand it correctly, if you use Get_the_author_meta() outside the loop, you need to specify the ID of the user? Pippin will know the answer, but I’m pretty sure you cant get the ID of a user using this function on a post?
      You could use it in the loop and I think it would work.
      On the post page, which I assume you are using this function on, you should already have the ID available to use:

      the_author_meta(‘ID’)

      I am not at home at the moment – and Pippin is the expert, but I think you need to replace your get_the_author_meta with the_author_meta as said above.

      The reason why you are getting the same number of followers etc for every user is because the way pippins plugin works is that if the function is not passed an ID it defaults to the current users ID. Your function does not pass an ID – so every user defaults to the currently logged in user – and for this reason when logged in as a user you will see all authors have the same number of followers etc.

      I think that I am right, but wait for confirmation.

  17. tommy80

    this code does not use it in the post page, I use it in the user profile which in my case is archive.php

  18. Peter Hudson

    I still think that your problem is the above – you are not passing the correct user id (or any at all) so it is defaulting to the logged in user id. I am happy to be wrong of course.

    Have you checked your database to see what data is actually being stored?

    I am not sure how you have a profile at the top of the archives page – I suppose it could be done but the archive template would be used for all posts not just a single author – so your template would need to check first that you were displaying a single authors posts – I would have thought you would set up an author template if you wanted a profile at the top.

    All that aside, it still makes me question again where your author ID is coming from – how the profile is displayed at the top of the page etc. Without looking at the template code its not easy to say.

    I suspect you are not using the get_user_meta in the loop – or anywhere where it will return an ID at the least.

  19. Peter Hudson

    If I was checking this myself I would echo the user ID the screen – so add to your code:

    echo get_the_user_meta(‘ID’);

    Switch to a few different authors and check that the ID that appears changes. If it stays the same, there’s your problem. If not it’s something else.

  20. Peter Hudson

    Sorry, of course I meant

    echo get_the_author_meta( β€˜ID’ ) ;

    • tommy80

      Peter Hudson you were right
      was a problem with id
      I solved… thanks again
      I put here my code so other users can use it

      $curauth = (isset($_GET[‘author_name’])) ? get_user_by(‘slug’, $author_name) : get_userdata(intval($author));

      $follow_unfollow = pwuf_get_follow_unfollow_links( $curauth->ID );
      echo $follow_unfollow;
      $following_count = pwuf_get_following_count( $curauth->ID );
      echo $following_count. ‘ following’;
      $follower_count = pwuf_get_follower_count( $curauth->ID );
      echo $follower_count. ‘ follower’;

    • Peter Hudson

      Good news πŸ™‚

  21. tommy80

    Peter Hudson thanks for the help… I will make new tests to see if the problem is what you think. As soon as I finish I write…

  22. Danniel Chiiko

    I am really new to WordPress and all these web technologies. Can someone please be kind enough to help me on how to create a button. i.e put the Follow/Unfollow words in a button? I know Pippin answered to my query last time but I really need some detailed advice.

    • Pippin

      Are you familiar with CSS?

  23. tommy80

    I had problems again with follow and unfollow
    to know if it’s just my problem I would empty all the follow / unfollow
    how can I clear them?
    through the database?

    • Pippin

      For a specific user or all users?

    • tommy80

      For all users

    • Pippin

      You will have to do it through the database by deleting all rows from wp_usermeta that have a meta_key of “_pwuf_following” and “_pwuf_followers”

    • tommy80

      it works, thanks πŸ˜‰

    • Pippin

      Great!

  24. tommy80

    Pippin, another thing: automatically send an email every time a user is added as following. Where and how can I? in functions.php?

    • Pippin

      Do you know how to use add_action()?

    • tommy80

      Not very well but I can try … I think I made things more difficult with wordpress πŸ™‚

    • tommy80

      Thanks Pippin, I try to make this work!

    • tommy80

      I did it! It ‘was hard work but it works πŸ™‚

    • Pippin

      Great to hear!

  25. Vajrasar Goswami

    Just one ques. In a previous part of the series, you mentioned to put a php chunk which will output follow/unfollow link beneath the post (single.php).

    Now, here you have setup the shortcodes for the same stuff. So does that mean, that now we can either use that php chunk or the shortcode, or am I missing something.

    Thanks for the awesome series.

    • Pippin

      Yep, either option works fine.

  26. Glenton Samuels

    I installed the plugin, but it doesn’t work when I added the PHP code to the single.php file. Not sure if I did anything wrong but the main reason I signed up for a membership is because I wanted this plugin.

    • Pippin

      Did you follow the tutorial series? The plugin is not meant as a plug-and-play plugin. It’s meant as a model to be used throughout the tutorial series that shows you how to build one from scratch.

  27. Argia Teknologi Nusantara

    Hello Pippin, is your plugin supports multisite ?

    • Pippin

      Yes it does.

  28. shubhra chaudhary

    Hi, hope you are well.

    I am showing a list of followers and following using get_users and in the foreach loop – pwuf_get_follow_unfollow_links( $follower_id ). The problem I am facing is when i click on the follow link for one user, the loading images for all users show up and all the follow links get toggled. $(‘.follow-links a’).toggle(); and $(‘img.pwuf-ajax’).show(); need to be attached with $this?

    • Pippin

      Sounds like you may just need to adjust the selector used in the JS to target only the one you clicked on. This was originally built with only one user’s links displayed on the page.

    • shubhra chaudhary

      I was able to work it out, thank you.
      I have a request. I am wondering if it is possible to show latest followers of a user with a count and when the user performs some action, like read/unread, decrease/increase the count. i.e. User B follows User A, User A is shown a notification bubble with ‘1’ as well as something like ‘User B is following you’, User A clicks on ‘Read’, count goes to zero. Something like buddypress. Can you provide me some direction on this please. Thanks.

Comments are closed.