50% discount on BricksLabs Pro Membership Lifetime Access. Use coupon: GOBRICKS

How to conditionally load your scripts based on an ACF field

Schermata-2022-07-25-alle-16.32.27

This tutorial provides the PHP codes that can be pasted in order to enqueue your scripts conditionally based on the value of an ACF field when using Bricks Builder.

Table of Contents

Requirements

  • Bricks Theme (any version)
  • Bricks Child Theme activated
  • ACF Free or Pro installed

Create a TRUE/FALSE custom field

The first thing to do is to create the custom field using ACF. We’ll use a TRUE/FALSE field and assign it to our pages and posts.

Apply the conditional enqueue in your child theme

Now open the functions.php file of your child theme and let’s write some PHP:

/**
 * Register/enqueue custom scripts and styles
 */
add_action( 'wp_enqueue_scripts', function() {
	// Enqueue your files on the canvas & frontend, not the builder panel. Otherwise custom CSS might affect builder)
	if ( ! bricks_is_builder_main() && class_exists( 'ACF' ) ) {
		// Child Theme Style.css
		wp_enqueue_style( 'bricks-child', get_stylesheet_uri(), ['bricks-frontend'], filemtime( get_stylesheet_directory() . '/style.css' ) );

		// HeadroomJS
		if ( get_field( 'activate_headroomjs' ) )  {
			wp_enqueue_script( 'headroom', get_stylesheet_directory_uri() . '/js/headroom/headroom.js', array(), '1.0.1' );
			wp_enqueue_script( 'headroom_init', get_stylesheet_directory_uri() . '/js/script.js', array( 'headroom' ), filemtime( get_stylesheet_directory() . '/js/script.js' ) );
		}

		// FullPageJS
		if ( get_field( 'activate_fullpagejs' ) ) {
			wp_enqueue_script( 'fullpage', get_stylesheet_directory_uri() . '/js/fullpage/fullpage.min.js', array(), '4.0.9' );
			wp_enqueue_style( 'fullpage', get_stylesheet_directory_uri() . '/css/fullpage/fullpage.min.css', '4.0.9' );
			wp_enqueue_script( 'fullpage_init', get_stylesheet_directory_uri() . '/js/fullpage_init.js', array( 'fullpage' ), filemtime( get_stylesheet_directory() . '/js/fullpage_init.js' ) );
		}
	}
});

As you can see, we wrapped our wp_enqueue functions inside an if statement:

  • if ( get_field('activate_fullpagejs' ) ) {...} for fullPageJS
  • if ( get_field( 'activate_headroomjs' ) ) {...} for Headroom.js

Activate/Deactivate your scripts on a page/post basis

If you correctly assigned your custom fields, you should see them at the bottom of your edit pages/posts:

Now you have a super easy one-click solution to enqueue the scripts you need on your different pages!

Conclusion

I often use this quick and dirty setup to have granular control over the scripts I run on each page and keep my websites as lightweight as possible. Happy enqueuing!

Leave your comment