简体   繁体   中英

Use IF condition inside a function that defines a hook

I am new to PHP. I am trying to use an IF condition inside a function. 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.

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.

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. 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. 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/

Different kinds of action hooks: https://codex.wordpress.org/Plugin_API/Action_Reference

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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