Thursday, 27 October 2016

Enqueuing Scripts Only When Widget Or Shortcode Is Present


WordPress developers really value loading scripts responsibly. But when you’re building a widget or a shortcode you don’t know where on the site it will be used. This article walks you through exactly how to enqueue your scripts and styles only if your widget or shortcode is present on the page. Why Do This?
Let’s say you are building a custom theme for a client. They want a certain styled content box to be used on different pages throughout the site. This is a great use for a shortcode
The TLDR; Version
Basically, all you need to do is use wp_register_script or wp_register_style anywhere in your plugin or theme. Then use wp_enqueue_scripts inside the function of your widget or shortcode output.
The Longform Version
First thing you need to understand is the difference between wp_register_script versus wp_enqueue_scripts. Here’s a quick list of functions/actions that are relevant to this discussion but are different enough that we really need to understand in order to do this right.
wp_enqueue_scripts — this is an ACTION. You use this to call a function that will trigger the next two items here.
wp_enqueue_script — this is a FUNCTION which does the
Source: https://managewp.org/articles/13709/enqueuing-scripts-only-when-widget-or-shortcode-is-present




source https://williechiu40.wordpress.com/2016/10/27/enqueuing-scripts-only-when-widget-or-shortcode-is-present/

No comments:

Post a Comment