• Resolved tribalcomm

    (@tribalcomm)


    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!

Viewing 5 replies - 1 through 5 (of 5 total)
  • Have you tried wp_print_scripts instead of wp_head?

    Thread Starter tribalcomm

    (@tribalcomm)

    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 here

    I 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.

    Thread Starter tribalcomm

    (@tribalcomm)

    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?

    Thread Starter tribalcomm

    (@tribalcomm)

    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!!!

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Why isn’t this function working?’ is closed to new replies.