helpful_has_user_voted

This can be used to display the vote status for a post and the current user. This is useful if you want to integrate Helpful into your WordPress theme and, for example, add a CSS class in the body tag.

This is how the function is structured:

/**
 * Checks by a Post-ID whether a vote has already been taken for this post.
 *
 * @global $post
 * @param int|null $post_id
 * @param bool $bool Returns the vote status (pro, contra, none) if true.
 * @return bool|string
 */
function helpful_has_user_voted($post_id = null, bool $bool = true)
{
    return Helpful_Helper_Values::has_user_voted($post_id, $bool);
}

This is how the function can be used:

global $post;

$post_id = $post->ID;

$status = helpful_has_user_voted($post_id, false);

echo $status; // pro, contra, none

$status = helpful_has_user_voted($post_id, true);

var_dump($status); // true, false

Thus, a CSS class can be attached to the body tag of the current page, depending on how a user has voted:

/**
 * @global $post
 * @param array $classes
 * @return array
 */
add_filter('body_class', function (array $classes) {
    global $post;

    if (isset($post->ID)) {
        $status = helpful_has_user_voted($post->ID, false);

        if ($status) {
            $classes[] = 'helpful--' . $status;
        }
    }

    return $classes;
});

This snippet adds the class .helpful--pro.helpful--contra or .helpful--none to the body tag of the current page.

Was this post helpful?

Top