Make WordPress Hooked Function to Run Only Once

by Yang Yang on December 12, 2012

Consider this hook to add something before your WordPress blog’s sidebar:

function before_siderbar() {
?>
<!-- Something goes here, such as an AdSense links unit -->
<?php
}
add_action( 'get_sidebar', 'before_siderbar' );

It’s usual to add an AdSense links unit there but the problem with some themes is that they run get_sidebar more than once, such as on the sidebar AND in the footer. Consequently, you would end up with multiple AdSense links unit here and there, whereas you only wanted it on the sidebar once.

This could create a TOS problem towards AdSense because unconsciously, you would very probably end up adding more than 3 links unit per page.

To prevent this and only make the hooked WordPress function to run once (even it is called multiple times), use the PHP static variable in functions.

function before_siderbar() {
	static $called = false;
	if (isset($called) && $called) {
		return false;
	}
?>
<!-- Something goes here, such as an AdSense links unit -->
<?php
	$called = true;
}
add_action( 'get_sidebar', 'before_siderbar' );

In the above snippet, the variable $called is kept alive across multiple calls to the before_siderbar() function. After the first successful run of the function, $called would have a value of true and it’s kept so inside the function every time it’s called afterwards. In the 2nd and every call afterwards, $called will always be true and the function returns before outputting the AdSense code.

There you go. Now no matter how many times the before_sidebar() is called, only the first run would output the stuff you put in it.

abdussamad December 16, 2012 at 10:48 pm

The isset() is kinda pointless since you are setting $called in the line before.

Hasitha March 24, 2013 at 3:26 pm

Thanks, its really helped me to clear things up.

Comments on this entry are closed.

Previous post:

Next post: