How to display content if user meta data isn’t empty with shortcode

Your shortcode can look like this:

[check-if-empty usermeta="last_name"] Is not empty [/check-if-empty]

The parameter called “usermeta” is added to your function ($atts) and it’s value is used to check the userdata.

function func_check_if_empty( $atts, $content = null ) { 
    if ( is_user_logged_in() ) { /* check if logged in */
        $user_meta = $atts['usermeta']; /* get value from shortcode parameter */
        $user_id = get_current_user_id(); /* get user id */
        $user_data = get_userdata( $user_id ); /* get user meta */
        if ( !empty( $user_data->$user_meta ) ) { /* if meta field is not empty */
            return $content; /* show content from shortcode */
        } else { return ''; /* meta field is empty */ }
     } else {
        return ''; /* user is not logged in */
     }
}
add_shortcode( 'check-if-empty', 'func_check_if_empty' );

We get the value using $atts['usermeta'] which is last_name in this example. After checking if the user is logged in we get the user data and use the meta field from your shortcode.

This way you can check all the meta fields (like first_name, user_login, user_email) with just using another value in your shortcode parameter called “usermeta”.

For example if you now want to display some content if the first name is not empty, you can just use this shortcode:

[check-if-empty usermeta="first_name"] Is not empty [/check-if-empty]