kylephillips / favorites

Simple and flexible favorite buttons for any WordPress post type.
https://favoriteposts.com
223 stars 86 forks source link

Getting the Favourite status of a post #107

Open gbowman85 opened 5 years ago

gbowman85 commented 5 years ago

I'm trying to get the status of any given post, i.e. whether the user has added it to favourites.

The reason is that I have set up the buttons to display how I want them on an individual post, and now I want to display the count of favourites in the metadata on an archive page. I want that count to show either a filled star or empty start, depending on whether the user has favourited it.

I've searched all through the documentation and support forum but can't find anything that seems to fit. I was expecting something like is_favourite() to return true or false.

I thought about returning the list of users who have favourited and comparing that with the current user or getting the list of favourited post and comparing that with the current post id. Is there a better way?

leorospo commented 5 years ago

Hi gbowman85 If i understood correctly you want to display a favourited icon or a non favorited icon in every element of an archive... I had to do something similar myself recently and i used in_array to check if the current post in the loop is or is not in the favourited array.

I use the function get_user_favorites() to get an array of user's favourited posts IDs

<?php
// I use the function get_user_favorites() to get an array of user's favourited posts IDs
        $bookmarked = get_user_favorites();

?>

I use in_array() to ceck if the current item in the loop is in the previous array

<?php
// I use in_array() to ceck if the current item in the loop is in the previous array
        in_array( get_the_ID(), $bookmarked ))

?>

So the full code wuold be:

<?php
            // I also check if the user is logged in because in my usecase only logged in users can favourite posts
        $bookmarked = get_user_favorites();
        if (is_user_logged_in() && in_array( get_the_ID(), $bookmarked )){ 
            // Do something if the post is bookmarked
            // Maybe print the filled star you refer to
        } else {
            // Do something if the post is not bookmarked or if the user is not logged-in
            // Maybeprint the empty star
        }?>

?>

I hope i've been helpful... This is one of my firsts answer over here

btw an off topic question... Does you name mean you sail?

gbowman85 commented 5 years ago

Thanks for your reply. That was one of the ways I'd thought about achieving this. Your code snippets are helpful, thanks!