kylephillips / favorites

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

Trying to cancel favorite #122

Open bash88 opened 5 years ago

bash88 commented 5 years ago

Hi,

First let me say, awesome plugin. Very versatile and easy to customize. Now for my issue.

I'm trying to cancel 'favoriting' a post when the user has a certain number of favorites. I found the favorites_before_favorite hook where I can attach my function. I see the updateFavorite function has a try catch, listening for an Exception which should cancel execution of the code entirely. I would think, at least.

Now when I throw the exception in favorites_before_favorite:

/**
 * Check for maximum number of preferences before favoriting
 *
 * @since 1.0.0
 */
public function my_check_max_preferences($post_id, $status, $site_id, $user)
{
    $max_preferences = get_option('my_general_options')['max_preferences'];

    if ( $max_preferences ) {
        $preference_count = get_user_favorites_count($user_id = null, $site_id = null, $filters = null, $html = false);
        if ( $preference_count == $max_preferences && $status == 'active' ) {
            throw new \Exception('Maximum number of preferences reached');
        }
    }
}

I see the error being returned in the admin-ajax.php request. However, the button on the frontend goes into a weird state where the favorite is saved but the total isn't updated and the js console throws an error:

favorites.js?ver=2.3.1:764 Uncaught TypeError: Cannot read property 'length' of undefined at Favorites.TotalCount.plugin.updateTotal (favorites.js?ver=2.3.1:764)

So updating the favorite never seems to be completely cancelled by the exception. Am I missing something, or is this a bug?

bash88 commented 5 years ago

Hi @GFargo, @kylephillips,

Could you please take a look at this? Thanks!

bash88 commented 4 years ago

@GFargo @kylephillips Would be much appreciated!