Skip to content

Instantly share code, notes, and snippets.

@danichim
Last active October 30, 2018 09:24
Show Gist options
  • Save danichim/50481ccf5d68b7e96c89b0dea509c817 to your computer and use it in GitHub Desktop.
Save danichim/50481ccf5d68b7e96c89b0dea509c817 to your computer and use it in GitHub Desktop.
shortcode To Show Or Hide Content
// Show or hide content based on whether user is logged in or not
// shortcode for logged in users is [loggedin]content[/loggedin]
// shortcode for logged out users us [loggedout]content[/loggedout]
function loggedincheck( $atts, $content = null ) {
$user = wp_get_current_user();
$allowed_roles = array('administrator', 'editor', 'author');
if ( is_user_logged_in() && !is_null( $content ) && !is_feed() && array_intersect($allowed_roles, $user->roles ) ) {
return $content;
return '';
}
}
add_shortcode( 'loggedin', 'loggedincheck' );
function loggedoutcheck( $atts, $content = null ) {
if ( !is_user_logged_in() && !is_null( $content ) && !is_feed() ) {
return $content;
return '';
}
}
add_shortcode( 'loggedout', 'loggedoutcheck' );
/*new version*/
function conditional_tags_shortcode( $atts, $content ) {
foreach ( $atts as $key => $value ) {
/* normalize empty attributes */
if ( is_int( $key ) ) {
$key = $value;
$value = true;
}
$reverse_logic = false;
if ( substr( $key, 0, 4 ) == 'not_' ) {
$reverse_logic = true;
$key = substr( $key, 4 );
}
// the conditional tag parameters
$values = ( true === $value ) ? null : array_filter( explode( ',', $value ) );
// check the condition
if ( preg_match( '/has_term_(.*)/', $key, $matches ) ) {
$result = has_term( $values, $matches[1] );
} elseif ( function_exists( $key ) ) {
$result = call_user_func( $key, $values );
}
if ( ! isset( $result ) )
return '';
if ( $result !== $reverse_logic ) {
return do_shortcode( $content );
}
}
return '';
}
add_shortcode( 'if', 'conditional_tags_shortcode' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment