Wordpress - How to use is_active_widget?
You should make the check inside the widget class, unless you don't have a choice. The example in the codex is pretty much what you're looking for:
class cbs_map_widget extends WP_Widget{
function cbs_map_widget(){
$this->WP_Widget('cbsmaps', __('Widget Name'), array('classname' => 'cbsmaps', 'description' => __('whatever')));
...
add_action('wp_enqueue_scripts', array(&$this, 'js'));
}
function js(){
if ( is_active_widget(false, false, $this->id_base, true) ) {
// enqueue your scripts;
}
}
...
}
The $widget_id
parameter is useful when you need to include your scripts only for a specific widget instance. For example when you have two cbs_map_widget
widgets and want to include custom javascript for each of them.
The $callback
argument is useful when you need to do the check outside the widget class (like you did above), but try to avoid it if you can do your check inside the class.
The other arguments are pretty much self explanatory (id_base is basically a "widget class indentifier", and the $skip_inactive
is whether to check inactive widgets as well - should be true because I don't think you want to do that)...
Edit: How to find the
$widget_id
(A widget instance ID)
Again, you don't need this unless you specifically want to check if a certain widget instance is active. Personally I use this method because I can access the instance options too:
...
function js(){
// we need to process all instances because this function gets to run only once
$widget_settings = get_option($this->option_name);
foreach((array)$widget_settings as $instance => $options){
// identify instance
$id = "{$this->id_base}-{$instance}";
// check if it's our instance
if(!is_active_widget(false, $id, $this->id_base)) continue; // not active
// instance is active
// access the widget instance options here, you may need them to do your checks
if($options['yourwidgetoption']) {
// do stuff
}
}
}
...
I was having the same problem, and I didn't find a good explanation about how the function works, because it seemed not to be working (always returns false in my case).
Looking at the source code, the function checks for two things basically, it checks if the $callbak
matches, and it checks if the $id_base
matches, if one of those matches, then it checks if the $widget_id
matches. So the param $id_base
must be filled to get it works with the $widget_id
.
Here is my example code:
$id_base = _get_widget_id_base($widget_id);
if(is_active_widget(false, $widget_id, $id_base)){
// Your code here ...
} else {
// Else code here ...
}