wp_enqueue_scripts hook is the proper hook to enqueue assets (despite the name, both CSS & JS) in the front end. However, if you enqueue assets this way, like all the examples on that documentation – the assets will be loaded on all pages on the front end. Here’s an example of how it’s usually enqueued.

wp_enqueue_script( 'wpfda-delete-account-frontend', plugins_url( 'assets/js/frontend.min.js', WPFDA_PLUGIN_FILE ), array( 'jquery' ), WPFDA_VERSION, false );

As a plugin developer, you might want to load assets conditionally only on pages which is using the plugin. Loading the assets on all other pages is unnecessary.

Conditional Load

To load assets when required, you can use the same hook “wp_enqueue_scripts” or “init” hook, and just register the script. Example:

wp_register_script( 'wpfda-delete-account-frontend', plugins_url( 'assets/js/frontend.min.js', WPFDA_PLUGIN_FILE ), array( 'jquery' ), WPFDA_VERSION, false );

and then you can just enqueue the script whenever you required. Usually, in the shortcode callback, while rendering the shortcode.

add_shortcode( 'footag', 'sa_footag_func' );
function sa_footag_func( $atts ) {
  wp_enqueue_script( 'wpfda-delete-account-frontend' );
	return "foo = {$atts['foo']}";
}

Or while rendering block, or wherever the plugin is being used in the front end. Just enqueue it because it’s already registered.

 wp_enqueue_script( 'wpfda-delete-account-frontend' );

Notes

In some cases, it might be too late to load the assets when rendering the content for your plugin or if something is loaded via AJAX or other edge cases scenarios I’m not aware of. For that, the “Load Assets Globally” option within your plugin is a good idea and could be useful for your users.

I hope this helps! If might also be interested in the article: avoid using wp_localize_script() everywhere.

Load Assets Conditionally in your WordPress Plugin
Tagged on:     

Sanjeev Aryal

Don't bury your thoughts, put your vision into reality ~ Bob Marley.

Leave a Reply

Your email address will not be published. Required fields are marked *

× WhatsApp