admin管理员组文章数量:1329040
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]
本文标签: How to display content if user meta data isn39t empty with shortcode
版权声明:本文标题:How to display content if user meta data isn't empty with shortcode 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742224765a2436046.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
last_name
or you want to check the field from the Wordpress user? – mozboz Commented Jul 28, 2020 at 14:44