Hey. You can add condition if ( is_page_template( 'your_custom_page_template.php' ) ) { wp_enqueue_your_style_and_scripts } in your wp_enqueue_scripts action
-
This reply was modified 5 years, 1 month ago by
pelukho.
@pelukho Sorry, I should have clarified….
The gallery template_part is inside my single.php.
So within single.php there is
if ($gallery_images) {
get_template_part('the_gallery_part')}
I think it would work if I just added enqueue_scripts/styles right inside the the_gallery_part, since it’s only called if there is a gallery…
It’s too late to enqueue for head section scripts, but it might work for footer scripts. A bit unorthodox, but give it a try! It might work. I’m rather skeptical it’ll work, but it wouldn’t be the first time I’m wrong.
FWIW, the “proper” way is to place the code in a plugin or a theme’s functions.php and then conditionally enqueue. I’m not sure if the template has been decided at that point, but you can condition upon get_queried_object_id() if not. It’ll generally return single post/page IDs, but might also return term archive IDs. You can check against get_queried_object() instead if you need to check for more than just the ID.
@bcworkz Okay that makes sense. So it sounds like I can check with get_queried_object_id() and from there, check if there is an (acf) gallery in the post: if there’s an ACF gallery I can enqueue the css/js early enough to hook the head?
If you need to check for an ACF gallery in content, you could get the queried object itself instead of just the ID. Then you can directly check its post_content property for the gallery. But wouldn’t the gallery presence be implicit in the IDs you are checking against? Lets say galleries exist in post IDs 12, 34, 56. You could do something like
if ( in_array( get_queried_object_id(), [12, 34, 56,]))
wp_enqueue_script('foo'); // script previously registered
Of course hardcoding IDs that have galleries would be difficult to maintain. It’d be better to get the IDs from somewhere easier to maintain. Either a manual settings field or maybe a transient option that’s regularly updated by a scheduled task which queries for such posts and saves the result.