Why isn’t this function working?
-
I have a site with multiple sidebars and I am making a widget that has some javascript in it that will only be on some pages. I am trying to set it up so that, if the widget is active on a page (through the sidebar that is loading in the template), it will add the javascript to the header. My current code is:
<?php function TCWidget(){ $widget_ops = array('classname' => 'widget_tc', 'description' => __( "My widget") ); $control_ops = array('width' => 200, 'height' => 150); $this->WP_Widget('tcwidget', __('TC Widget'), $widget_ops, $control_ops); if ( is_active_widget() ) add_action('wp_head', 'tc_widget_header'); } function tc_widget_header() { ?> <script type="text/javascript" language="javascript" src="myscript.js"></script> <?php }The problem is the script never appears in the header, whether the widget is in the sidebar or not.
Please help, as this is driving me insane!!!
Thanks!
-
Have you tried
wp_print_scriptsinstead ofwp_head?I am trying that, but I realized that the is_active_widget will put it in the header of every page as long as the widget is active anywhere, but this is preloading a bunch of images, so I don’t want it on any page but the ones where the widget is displayed.
I am trying wp_print_scripts, but it still isn’t showing. I am trying to add it to the actual widget code, so it runs when the widget is displayed. It this possible?
i.e.
function widget($args, $instance){ extract($args); # Make the widget ?> <?php echo $before_widget; ?> <?php wp_print_scripts ('myscript', WP_PLUGIN_URL . "/myplugin/scripts/myscript.js"); ?> Widget content hereI meant to try to use wp_print_scripts in your add_action–
add_action('wp_print_scripts', 'tc_widget_header');.Functions like is_page() will work inside the widgets. For example,
if (is_page('directory')) echo 'directory';will only echo content when on the ‘directory’ page.Nothing seems to be working with this…
where should I put it so that it loads only on the pages that the widget is actually displayed?
SOLVED!
I put
add_action('wp_head', array(&$this, 'tc_widget_header') );into the widget contruct function then defined the function echoing all the scripts I need, and now it is loading only on the pages that the widget is displayed.Thanks!!!
The topic ‘Why isn’t this function working?’ is closed to new replies.