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

I need to display content if user meta data isn’t empty

Example :

[empty_user_meta="last_name"]
Show only if last_name is not empty. 
[/empty_user_meta]

Code don’t work :

    add_shortcode( 'empty_user_meta', 'user_meta_empty' );
function user_meta_empty( $atts, $content ) {
   extract(
      shortcode_atts( array( 'meta' => '' ), $atts )
   );
   $meta = explode ($atts['meta'] );
 
   foreach ( $meta as $value ) {
      $value = trim( $value );
      if ( ! empty( $value ) ) {
         return $content;
      }
   }
   return '';
}

Can anyone help me?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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]


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x