Skip to content

Instantly share code, notes, and snippets.

@ipokkel
Last active June 21, 2023 14:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ipokkel/40b22fe5e01a34ae6d6553ffbb7e39fd to your computer and use it in GitHub Desktop.
Save ipokkel/40b22fe5e01a34ae6d6553ffbb7e39fd to your computer and use it in GitHub Desktop.
[membership_expired] shortcode
<?php
/**
* Add a shortcode to display content to members with an expired membership.
*
* Usage Example:
* [membership_expired]Shows if user's level expired[/membership_expired]
* [membership_expired level="1"]Shows if user's expired level ID matches[/membership_expired]
* [membership_expired levels="1, 2"]Shows if user's expired level ID matches one of the levels[/membership_expired]
*
* @param string $atts Shortcode level/levels IDs attributes.
* @param string $content Content between shortcode tags.
*/
function my_pmpro_shortcode_membership_expired( $atts, $content = null ) {
global $wpdb, $current_user;
// set default attributes and values
extract(
shortcode_atts(
array(
'level' => null,
'levels' => null,
),
$atts
)
);
//if levels is used instead of level
if ( isset( $levels ) && ! isset( $level ) ) {
$level = $levels;
}
//figure out which level/levels to check
if ( ! empty( $level ) || $level === '0' || $level === 0 ) {
//they specified a level(s)
if ( strpos( $level, ',' ) ) {
//they specified many levels
$levels = explode( ',', $level );
} else {
//they specified just one level
$levels = array( $level );
}
} else {
//didn't specify a membership level, so use false so pmpro_hasMembershipLevel checks for any level
$levels = false;
}
// if the user has an active membership, return empty string
if ( ! function_exists( 'pmpro_hasMembershipLevel' ) || pmpro_hasMembershipLevel() ) {
return '';
}
// Were they a member before?
$expired_level_id = $wpdb->get_var( $wpdb->prepare( "SELECT membership_id FROM {$wpdb->pmpro_memberships_users} WHERE user_id = %d AND status = 'expired' ORDER BY id DESC LIMIT 1", $current_user->ID ) );
// if they were not a member before, return empty string
if ( empty( $expired_level_id ) ) {
return '';
}
// if membership level is specified, return empty string if the user had a different membership level.
if ( ! empty( $levels ) && ! in_array( $expired_level_id, $levels, true ) ) {
return '';
}
if ( ! empty( $content ) ) {
$content = '<div class="my-pmpro-membership-expired">' . $content . '</div>';
}
// if the user has an expired membership, return the content
return do_shortcode( $content );
}
add_shortcode( 'membership_expired', 'my_pmpro_shortcode_membership_expired' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment