Monday, July 11, 2022
HomeWordPress Developmenthooks - Is it potential so as to add the_content filter upon...

hooks – Is it potential so as to add the_content filter upon login?


You have misunderstood how hooks, and PHP, work.

Hooks usually are not persistent. Every time you go to a web page in WordPress the PHP scripts that comprise WordPress all get run. Each time. This contains plugins and the theme’s the features.php file. So once you run add_action() that queues up a callback perform to run every time the corresponding do_action() is run. As soon as every little thing has run and the web page has rendered nothing is remembered. The one persistent info is no matter will get saved within the database, and hook callbacks usually are not saved within the database.

So, should you attempt to run add_filter( 'the_content', 'my_function', 10, 1 ); on wp_login, the my_function() callback will solely be utilized to the_content if the the_content is displayed for that single request the place the consumer is logged in. That is virtually definitely by no means going to occur as a result of customers are usually redirected after being logged in, and that redirect is a separate request.

What you’re truly making an attempt to do is filter the_content if the present consumer is logged in. The correct means to do this is to test if the consumer is logged in inside my_function() and so as to add your filter for each request:

perform my_function( $content material ) {
    if ( is_user_logged_in() ) {
        // Do one thing with $content material.
    }

    return $content material;
}
add_filter( 'the_content', 'my_function' );

Word that add_filter() is on the ‘prime degree’, and never inside one other hook. It’s going to run on each request, however the content material will solely be modified if the consumer is logged in. Additionally be aware that we used is_user_logged_in() inside the callback perform, as a substitute of round add_filter(). It’s because when add_filter() can be run it hasn’t been decided if the consumer is logged in or not but.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments