Add a Lock Icon to WooCommerce Memberships Restricted Posts June 14 2017

The post Add a Lock Icon to WooCommerce Memberships Restricted Posts appeared first on SkyVerge.

We’ve gotten this question a few times, most recently from Jon:

Can I add a lock icon before restricted posts? I already use FontAwesome, but I’m not sure how to add / remove the lock depending on whether the customer has access.


Definitely do-able As Jon has noted though, be sure that FontAwesome is already loaded on your site so the icon can be shown.

To add the icon, we’ll filter the_title to adjust the post title. We’ll need to (a) be sure avoid running this in the WordPress admin, and (b) show this icon if access is restricted or delayed.

/**
 * Display a FontAwesome lock icon next to the post title if a member does not have access
 *  with WooCommerce Memberships.
 *
 * @param string $post_title the post title
 * @param int $post_id the WordPress post ID
 * @return string the updated title
 */
function sv_wc_memberships_add_post_lock_icon( $title, $post_id ) {

    if ( is_admin() ) {
        return $title;
    }

    // show the lock icon if the post is restricted, or access is delayed
    if (   ! current_user_can( 'wc_memberships_view_delayed_post_content',    $post_id )
        || ! current_user_can( 'wc_memberships_view_restricted_post_content', $post_id ) ) {

        $title = "<i class='fa fa-lock' aria-hidden='true'></i> {$title}";
    }

    return $title;
}
add_filter( 'the_title', 'sv_wc_memberships_add_post_lock_icon', 10, 2 );

That’s it Now, if a non-member views the site, any restricted post will show the lock icon + a title.

WooCommerce memberships: Non member view

Non-member view

If a member logs in, they’ll see the normal title, or will still see a lock icon if they (a) can’t access the post, or (b) will be able to access it, just not yet:

WooCommerce Memberships lock icon member view

Member view

This will only work for posts (or content Memberships treats like posts), not products, but the capabilities checks could be extended if you wanted to check other types of content.

View the full snippet here.

The post Add a Lock Icon to WooCommerce Memberships Restricted Posts appeared first on SkyVerge.