The constructor of widget is called when the widget is registered, so your add_action
is called on (probably) every request. You can avoid that simply put the add_action
inside widget()
function, that is called only when the widget is printed so there is no need to check: just output what you want.
Also, if you need some context inside the footer
method you can use a closure inside the widget
method where you have easy access to $args
and $instance
variables (the first contain information about the sidebar and the widget id, the second contain informations on the fields setted for speficic widget):
class CustomWidget extends WP_Widget {
function __construct() {
parent::__construct( 'my-widget-id', 'My Widget Name' );
}
function widget( $args, $instance ) {
add_action( 'wp_footer', function() use ( $args, $instance ) {
echo '<h1>' . $args['widget_id'] . '</h1>';
echo '<pre>'; print_r( $instance ); echo '</pre>';
echo '<pre>'; print_r( $args); echo '</pre>';
echo '<hr>';
});
}
function update( $new_instance, $old_instance ) {}
function form($instance) {}
}
that makes the closure all the times the widget is added to page, i.e. if the widget is added 3 times, the closure will run 3 times.
If you want to prevent that use a static flag:
class CustomWidget extends WP_Widget {
static $added = 0;
function __construct() {
parent::__construct( 'my-widget-id', 'My Widget Name' );
}
function widget( $args, $instance ) {
add_action( 'wp_footer', function() use ( $args, $instance ) {
if ( static::$added !== 0 ) return; // run only once;
static::$added++;
echo '<h1>' . $args['widget_id'] . '</h1>';
echo '<pre>'; print_r( $instance ); echo '</pre>';
echo '<pre>'; print_r( $args); echo '</pre>';
echo '<hr>';
});
}
function update( $new_instance, $old_instance ) {}
function form($instance) {}
}
PS: PHP 4 died a long time ago. Please use PHP 5 constructors…