Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress: enqueue a script only if a widget is used

There is a way to enqueue a script only if a widget is used (pay attention, not if is active, but if it is present inside a sidebar in a page/post)? Or even better: there is a way to enqueue a script only if a particular string appears inside a sidebar?

like image 316
pixedelic Avatar asked Dec 13 '22 10:12

pixedelic


2 Answers

Just enqueue the script or stylesheet in the widget function. This is the easiest and best approach.

    public function widget( $args, $instance ) {
        // outputs the content of the widget

        // Enqueue a script needed for
        // the Widget's output
        wp_enqueue_script( 'your_script', $path, $deps );

        // Rest of widget output goes here...
    }
like image 175
Kyle King Avatar answered Dec 29 '22 08:12

Kyle King


I haven't actually tested, this but one possible solution would be to enqueue your script to the footer.

If widget is used

When you build the widget, you can add some code to the widget() function of your widget's class (the function at actually outputs the widget to the screen). You could call wp_enqueue_script() from here, just make sure you flag it to be used in the footer.

This will print your script where wp_footer() is called rather than where wp_head() is called, but only if the widget is invoked on the page.

If a string appears in the sidebar

Basically, just filter the sidebar for your string. If the string is present, enqueue your script to the footer the same way you would with a widget.


(Update) Alternatives

There are two other things you can do. First, you can use jQuery to namespace your functionality. Basically, give your widget a unique ID (say "my-unique-id"), then download your script asynchrounously:

jQuery(document).ready(function() {
    if( jQuery('#my-unique-id').length > 0 ) {

        jQuery.getScript( [your-script-url] );

    }
}

This code will check to see if your widget ID is on the page ... if so, it downloads your script from the server, if not, it does nothing. You can also build this code in PHP to include either a relative or absolute reference to your script file. It's up to you.

Alternatively, you could just include your script in an inline <script> block in your widget's code. This will work the way you want it to, but it breaks all kinds of standard coding practices. Code should typically be in the <header> or placed directly before the closing </body> tag ... but you can really put it anywhere you want.

like image 30
EAMann Avatar answered Dec 29 '22 07:12

EAMann