Wordpress init hook called multiple times
10,744
function my_setup() {
echo 123 . '<br />';
}
add_action('init', 'my_setup');
I see 123 appear once only. Init should not run more than once, and does not on my installation.
However i think you'll find the clue you're looking for in Rob's Answer to Wordpress why is the init hook invoked multiple times.
Hope that helps.
Author by
John Doe
Updated on June 05, 2022Comments
-
John Doe almost 2 years
I did a fresh installation of wordpress 3.0.4 and attempted to write a simple theme for just the sake of trying.
In functions.php, I created a function called my_setup and hooked it up to init. I noticed that my_setup() is called multiple times and I tried to use a global flag variable to control the execution of the function but to no avail. How do I ensure that my function is only called once?
<?php // global variables $setup_run_before = 0; ?> <?php function my_setup() { global $setup_run_before, $a; if($setup_run_before == 0) { $setup_run_before = 1; // this section is always called even with global variable. } } ?> <?php add_action('init', 'my_setup'); ?>
Regards, John Doe
-
BonisTech over 3 yearsYou won't see the output as many times as init is called. Php may run many times on the server, but it will output the code just one time. Your approach was good. But try debugging with a log file and you'll probably get another output: file_put_contents('./log_'.date("j.n.Y").'.log', 'foobar'.PHP_EOL, FILE_APPEND);