Wordpress: enqueue a script only if using a widget

Is there a way to insert a script only if a widget is used (note, not if it is active, but if it is present inside the sidebar on the page / post)? Or even better: is there a way to insert a script only if a specific line appears inside the sidebar?

+4
source share
3 answers

Just enter a script or style sheet 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 output wp_enqueue_script( 'your_script', $path, $deps ); // Rest of widget output goes here... } 
+9
source

I did not actually test this, but one possible solution would be to insert your script in the footer.

If using a widget

When creating a widget, you can add code to the widget() function of your widget class (the function actually displays the widget on the screen). You can call wp_enqueue_script() here, just make sure you mark its use in the footer .

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

If a line appears in the sidebar

Basically, just filter the sidebar for your row. If the line is present, enter the script in the footer in the same way as with widgets.


(Refresh) Alternatives

There are two more things you can do. First, you can use jQuery to namespace your functionality. Basically, give your widget a unique identifier (say, "my-unique-id"), and then load the script asynchronously:

 jQuery(document).ready(function() { if( jQuery('#my-unique-id').length > 0 ) { jQuery.getScript( [your-script-url] ); } } 

This code checks if your widget id is on the page ... if so, it loads your script from the server, if not, it does nothing. You can also create this code in PHP to include either a relative or an absolute link to your script file. It depends on you.

Alternatively, you can simply include your script in the built-in <script> block of your widget code. This will work the way you want it, but it violates all kinds of standard encoding methods. The code should usually be located in <header> or placed immediately before the closing </body> ... but you can put it anywhere.

+2
source

Yes.

I reviewed "wp_footer" because this hook is executed under the footer and probably the best way to add scripts only where the widget is used.

 class Your_Widget extends WP_Widget{ function widget( $args, $instance ) { add_action('wp_footer',array($this,'front_end_scripts')); } function front_end_scripts(){ ?><script type="text/javascript"> console.log('this works!'); /* Or if you need external scripts then you may use $.getScript([your-script-url] ); */ </script> <?php } } 
+2
source

Source: https://habr.com/ru/post/1369001/


All Articles