简体   繁体   English

在定义挂钩的函数中使用IF条件

[英]Use IF condition inside a function that defines a hook

I am new to PHP. 我是PHP新手。 I am trying to use an IF condition inside a function. 我正在尝试在函数内使用IF条件。 The function originally contains a hook which works well without the IF condition, but I need the IF condition to display this hook to only site visitors who are not logged in. 该函数最初包含一个挂钩,该挂钩在没有IF条件的情况下也能很好地工作,但是我需要IF条件才能将此挂钩仅显示给未登录的站点访问者。

What is wrong with my code, please? 请问我的代码有什么问题?

I have been able to display the function in a template without any problems. 我已经能够在模板中显示该功能,而没有任何问题。 But the function is supposed to be displayed to only logged out users, and I have tried adding an IF condition to achieve this, all to no avail. 但是应该只向注销的用户显示该功能,而我尝试添加IF条件来实现此目的,但无济于事。

function add_signup_notice_after_excerpt_two() 
{
    if ( !is_user_logged_in() ) {
        echo '//Some HTML'
    }; 
    else{
    };

    add_action( 'signup_notice_after_excerpt_two', 'add_signup_notice_after_excerpt_two', 5 );
}

I expected the hook to display the HTML code in the IF condition when used in the template, but it did not display. 我希望该钩子在模板中使用时会在IF条件下显示HTML代码,但不会显示。 However, the hook worked in the template without the condition. 但是,该钩子可以在没有条件的情况下在模板中工作。

Try the following code: 尝试以下代码:

function add_signup_notice_after_excerpt_two() 
{
    if ( !is_user_logged_in() ) {
        echo 'Some HTML'; } 
    else{

    }
}

add_action('wp','add_signup_notice_after_excerpt_two', 5 );

The bug was, You have created a function but you did not Hook add_signup_notice_after_excerpt_two() on to a specific action and that add_action() must be out side the function in your case. 错误是,您已经创建了一个函数,但是没有将add_signup_notice_after_excerpt_two()到特定action并且在您的情况下add_action()必须在该函数之外。 And there had some syntax errors in your code. 而且您的代码中存在一些语法错误。

Go through the following link. 通过以下链接。

How to add an actoin : https://developer.wordpress.org/reference/functions/add_action/ 如何添加actoin: https : //developer.wordpress.org/reference/functions/add_action/

Different kinds of action hooks: https://codex.wordpress.org/Plugin_API/Action_Reference 不同类型的动作挂钩: https : //codex.wordpress.org/Plugin_API/Action_Reference

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM