Today’s customization will feature a custom shortcode that you can use to display content only to logged in customers: [customers-only]content for customers here e.g. video iframe[/customers-only]
This is perfect for membership sites, LMS platforms, paywalled content.
In my case, only premium Club members with a ‘CLASS’ pass can watch upcoming WooCommerce masterclasses and past recordings, so I needed the shortcode to hide the video to logged out users or logged in customers without a pass.
By wrapping the video iframe HTML inside the shortcode, I can show the video to logged in customers who purchased a given product ID, or alternatively show an error message, which you can see in action here, in the “The recording is now available!” section: https://www.businessbloomer.com/class/behind-the-scenes-how-i-run-business-bloomer/
So, how did I do it? Find out below, and hope you can use it too!
PHP Snippet: Shortcode to Display Conditional Content to Logged In Customers Who Purchased a Specific Product
/**
* @snippet Customer Conditional Content Shortcode
* @usage [customers-only]content[/customers-only]
* @tutorial Get CustomizeWoo.com FREE
* @author Rodolfo Melogli
* @compatible WooCommerce 8
* @community https://businessbloomer.com/club/
*/
add_shortcode( 'customers-only', 'bbloomer_conditional_content_club_members_only' );
function bbloomer_conditional_content_club_members_only( $atts, $content = "" ) {
// RETURN ERROR MESSAGE IF LOGGED OUT OR DID NOT PURCHASE PROD ID 12345
if ( ! is_user_logged_in() || ! wc_customer_bought_product( '', get_current_user_id(), 12345 ) ) return '<div class="woocommerce-error"> Sorry, this video is only visible to <b>logged in Business Bloomer Club members with a "<i>CLASSES</i>" or "<i>SPONSOR</i>" pass</b>.<br>If you joined already, please <a href="' . esc_url( wc_get_page_permalink( 'myaccount' ) ) . '">log in</a>.<br>Otherwise, here are 5 reasons you should <a href="/club/">join the Club</a>.</div>';
// OTHERWISE RETURN CONTENT
return $content;
}