Forums

[resolved] Why isn't this function working? (6 posts)

  1. tribalcomm
    Member
    Posted 4 weeks ago #

    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!

  2. apljdi
    Member
    Posted 3 weeks ago #

    Have you tried wp_print_scripts instead of wp_head?

  3. tribalcomm
    Member
    Posted 3 weeks ago #

    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
  4. apljdi
    Member
    Posted 3 weeks ago #

    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.

  5. tribalcomm
    Member
    Posted 3 weeks ago #

    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?

  6. tribalcomm
    Member
    Posted 3 weeks ago #

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

Reply

You must log in to post.

About this Topic