前言问题描述
需求 wordpress需要在用户是登录状态的时候显示用户名,如果没有登录就显示别的东西,由于wordpress古腾堡编辑器,以及elementor页面构造器,没找到需要的功能,所以通过自定义段代码来实现
// 段代码函数,放在主题文件夹里面的functions.php里面,如果你的主题有跟新需求,
// 最好是找个插件追加到这个文件当中,因为跟新主题的时候可能会被覆盖
function wpb_demo_shortcode()
{
//wordpress自带的获取登录用户的函数,返回对象数组。
$message = wp_get_current_user();
//拿到用户id,如果等于零表明用户没有登录,否则用户就是登录状态,然后拿到用户名。
if( 0 == $message->Id){
echo '<div style="font-size: 35px;">
<a href="******">Please click to login</a>
</div>';
} else {
echo '<div style="font-size: 35px;">Username: '. $message->user_login .'</div>';
}
}
// 注册短代码
add_shortcode('UserName', 'wpb_demo_shortcode');
简而言之就是写一个函数放在注册一下就好了,最后放到functions.php文件里面
如果发现内容出现在了外面请使用return进行返回内容,不要使用echo
function get_user_point_msg2 (){
$message = wp_get_current_user();
$userId = $message->ID;
global $wpdb;
$results = $wpdb->get_results('SELECT t2.creds, t1.time, t1.entry FROM wp_mycred_log t1, ( SELECT SUM( creds ) creds FROM wp_mycred_log WHERE user_id = '. $userId .' ) t2 WHERE t1.user_id = '. $userId .' ORDER BY t1.time DESC LIMIT 0,1;', OBJECT);
$time = $results[0]->time;
return date('m-d-Y H:i',$time) . " pm";
}
add_shortcode('user_point_msg2', 'get_user_point_msg2');