如何仅在用户注销/未注册时才向模板添加HTML

时间:2017-07-03 作者:D.Wells

我正在尝试仅当用户注销时才将登录/注册按钮添加到我的主页。我已经尝试在相关模板中使用do\\u shortcode调用:(我知道目前没有条件检查是否登录,但我只是想首先确保shortcode实际工作)

add_shortcode(\'loginout_button\',\'add_loginout_button\');

function add_loginout_button {
$content = \'<div style="text-align:center;background-color:#7114B7;padding:15px;border-radius:50px;margin:20px;"><a href="">
                LOGIN/REGISTER
                </a>  
                </div>\';
return $content; 
}
然后使用

echo do_shortcode(\'[loginout_button\']);
在模板中,但短代码没有注册-它只是响应[loginout\\u按钮]。我想这不是办法!我是否必须先使用过滤器,然后再应用\\u过滤器?这在我的脑海中是有道理的,但我现在真的需要一些帮助-提前谢谢!

2 个回复
最合适的回答,由SO网友:Junaid 整理而成

首先,您的快捷码使用代码不正确,正确的代码是:

echo do_shortcode(\'[loginout_button]\');
现在,如果你想回应login/logout 按钮仅当用户未登录时,才可以使用该功能is_user_logged_in(). 有两种方法可以做到这一点

1) 。短代码中的条件逻辑。

add_shortcode(\'loginout_button\',\'add_loginout_button\');
function add_loginout_button() {
    if ( is_user_logged_in() ) {
        return \'<div style="text-align:center;background-color:#7114B7;padding:15px;border-radius:50px;margin:20px;"><a href="">LOGIN/REGISTER</a></div>\';
    }
    return false;
}
这是推荐的方法,因为您可以在任何地方使用短代码并获得预期的结果。

2) 将您的短代码使用代码包装在条件标记中

if ( is_user_logged_in() ) {
    echo do_shortcode(\'[loginout_button]\');
}

SO网友:dbeja

您是否复制/粘贴了正确的代码?

add\\u loginout\\u按钮上缺少括号。它应该是:

function add_loginout_button() {
$content = \'<div style="text-align:center;background-color:#7114B7;padding:15px;border-radius:50px;margin:20px;"><a href="">
                LOGIN/REGISTER
                </a>  
                </div>\';
return $content; 
}
这应该添加到函数中。php。

您还可以检查用户是否登录is_user_logged_in():

add_shortcode(\'loginout_button\',\'add_loginout_button\');

function add_loginout_button() {
    if( is_user_logged_in() ) {
        $content = \'<div style="text-align:center;background-color:#7114B7;padding:15px;border-radius:50px;margin:20px;"><a href="">LOGIN/REGISTER</a></div>\';
    } else {
        $content = \'\';
    }

    return $content; 
}

结束

相关推荐

Using shortcode in Post title

我有很多帖子,其中我有本月的帖子标题。当月底,手动更改所有帖子有点烦人。因此,我创建了一个短代码来显示当前月份。我使用了add_filter( \'the_title\', \'do_shortcode\' );执行标题中的短代码。一切正常。问题是,在元标题中,显示的是原始短代码,而不是输出。有什么建议可以帮我解决吗。提前谢谢。