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?
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?
Share Improve this question edited Jul 28, 2020 at 14:41 Olivier asked Jul 28, 2020 at 14:35 OlivierOlivier 196 bronze badges 2 |1 Answer
Reset to default 0Your 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]
last_name
or you want to check the field from the Wordpress user? – mozboz Commented Jul 28, 2020 at 14:44