php - Enqueue sripts and styles only if function is called

admin2025-04-19  0

I'm using a function to display a gallery and I need to load its JS/CSS only if the gallery function is called. Both functions are in the custom plugin.

I have now the first function to enqueue scripts and styles and function itself:

function gallery_assets() {
            $upload_dir = wp_get_upload_dir();
            wp_enqueue_style('flex-gallery', trailingslashit( $upload_dir["baseurl"]).'gallery-assets/css/flex-gallery.css');

            wp_enqueue_script('flex-gallery-jquery', trailingslashit( $upload_dir["baseurl"]).'gallery-assets/js/jquery.min.js');
            wp_enqueue_script('flex-gallery', trailingslashit( $upload_dir["baseurl"]).'gallery-assets/js/flex-gallery.js');
            } 
add_action( 'wp_enqueue_scripts', 'gallery_assets', 10);
function portfolio_gallery () {}

My question is: How I can execute gallery_assets() from portfolio_gallery()?

Thank you!

I'm using a function to display a gallery and I need to load its JS/CSS only if the gallery function is called. Both functions are in the custom plugin.

I have now the first function to enqueue scripts and styles and function itself:

function gallery_assets() {
            $upload_dir = wp_get_upload_dir();
            wp_enqueue_style('flex-gallery', trailingslashit( $upload_dir["baseurl"]).'gallery-assets/css/flex-gallery.css');

            wp_enqueue_script('flex-gallery-jquery', trailingslashit( $upload_dir["baseurl"]).'gallery-assets/js/jquery.min.js');
            wp_enqueue_script('flex-gallery', trailingslashit( $upload_dir["baseurl"]).'gallery-assets/js/flex-gallery.js');
            } 
add_action( 'wp_enqueue_scripts', 'gallery_assets', 10);
function portfolio_gallery () {}

My question is: How I can execute gallery_assets() from portfolio_gallery()?

Thank you!

Share Improve this question asked Oct 23, 2019 at 15:09 JaroJaro 11 bronze badge 1
  • How is portfolio_gallery called? – czerspalace Commented Oct 23, 2019 at 17:22
Add a comment  | 

2 Answers 2

Reset to default 0

Instead of two functions, just put the gallery assets code inside of the portfolio gallery function.

Or nest it. Nesting is kinda ugly though.

My question is: How I can execute gallery_assets() from portfolio_gallery()?

Unfortunately, you haven't given any indication as to how portfolio_gallery() is executed. Is it called from another function/location? Or is it hooked to something?

It's actually more than likely that you don't need to execute gallery_assets() from portfolio_gallery(). If portfolio_gallery() runs in the body (such as displaying content), gallery_assets() it would already have executed. You've hooked it to the wp_enqueue_scripts action, and as written, it will execute in the head.

This page in the Codex has a general list of actions and the order they come in.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745057638a282499.html

最新回复(0)