Discover in this tutorial how to display a list of your subscribers’ favorite posts using code.
You already know that in OsomCode you can bookmark your favorite or most used tutorials to have them just a click away, right?
In fact, at the request of several subscribers I dedicated a tutorial in which I explained how to create a plugin that allows you to do so.
If you are already using it in a project, I’m sure that what I’m going to explain today will interest you. And if you are not using it yet, it is possible that after today you will find it more interesting.
The plugin we created allows the subscribers to visit their account and find their favorite tutorials quickly and easily:
And in this new tutorial you are going to see how to show a TOP list of the tutorials that more subscribers have decided to add as favorite. Interesting, isn’t it?
Read on to apply it to your projects.
Steps to create a list of your subscribers’ favorite posts
1. Create the shortcode
We will choose to encapsulate all the logic necessary to display the list within a shortcode, so we can display it anywhere on the web.
Add the following code snippet to your functionality plugin:
To see this and another 1097 code snippets of this website, login or subscribe here.
The above snippet performs several functions:
- A loop that goes through all users and extracts the values from the cg_favorite_post metadata using
get_user_meta
. - Since there can be several per user, it gets an array for each user.
- It collects all the arrays using
array_merge
. - Perform a count to know how many times is there each post using
array_count_values
. - Sort the array of posts with more favorites to less thanks to
arsort
. - Once the data is in the order and format that interests you, it executes another loop in which it extracts the value of the first 10 elements of the array with the function
array_keys
. These are the ID of the post. - With the ID of the posts, it obtains the title and the URL and places them inside an ordered list.
If you are using your own version of the plugin and have used another name for the metadata that stores favorite posts, just replace cg_favorite_post
with your own.
2. Add the shortcode to display subscribers’ favorite posts
Finally, if you want a page to display the user’s favorite posts, add the shortcode [[top_favorite_posts]]
to it.
Now you just need to link that page in the menu (or wherever you want) so that the user can access it easily.
Conclusions
Now you know how to display a list of the posts that your subscribers (or your customers) have saved most often as favorites using a shortcode.
Also, this example can serve as a guide to create similar lists based on other metadata. 😉
Any questions? Let me know in the comments.
And if you want to give me any suggestion for future tutorials, leave it in the contact form. Advantages of being a subscriber. 😉