Search code examples
phpwordpressadvanced-custom-fields

Enqueue script based on ACF value


So I wanted to see if this is possible and how I might be able to solve this - But here is what I am using:

I have one ACF group created, that has two fields:

  • Enable OneTrust, name: enable_onetrust, Radio Button
  • Script Tag, name: onetrust_script_tag, Text Area

When I add in the <script> tag provided by OneTrust, it auto enqueues and renders on the front-end and build out the Object, so I am not calling wp_enqueue_script on it at all in the functions.php file.

Here is the setup in the UI:
enter image description here

What I want to do is create a conditional, that when enable_onetrust is set to no/false, don't enqueue the script, otherwise enqueue it.

Since the script isn't being called using wp_enqueue_script anywhere, how do we go about doing this?


Solution

  • You have to check for the field value of you enable OneTrust field. I would use a true/false field for that.

    If you have a true/false field you can do this:

    <?php 
    function my_assets() {
    
        $enable_onetrust = get_field('enable_onetrust'); 
    
        if ( $enable_onetrust == true ) :
            wp_enqueue_script( 'onetrust', 'PATH-TO-JS', , false, true );
        }
        endif;
    
    add_action( 'wp_enqueue_scripts', 'my_assets' );
      
    ?>
    

    And for the other script you can use something like this:

    <?php 
    add_action( 'wp_footer', function() {
        $enable_onetrust = get_field('enable_onetrust'); 
    
        if ( $enable_onetrust == true ) : ?>     
    
            <script>
                // Your Script
            </script>
    
        <?php endif; ?>
    
    <?php }, 99 );