WeebleWobb WeebleWobb - 1 month ago 10
jQuery Question

Pulling PHP data into JS to dynamically change BG image on screen width

In my WP Template I created two Sub fields in my Repeater custom fields for bg imgs:


  1. The large device and desktop bg

  2. The mobile bg



In my
content-section.php
template part, I created a loop and inject
get_sub_field('background_image');
as a bg image successfully. I'd like to dynamically change the bg-img to mobile when the width is
< 768
. I know you have to pass the php data over to js by using
wp_localize_script()
etc..

What I've tried:


  1. Set a var for
    get_sub_field('mobile_background_image');
    in
    content-section.php

  2. Used different variation of AFC Functions to pull bg data in
    functions.php
    :
    the_field('mobile_background_image')
    ,
    get_sub_field('mobile_background_image')
    ,
    the_sub_field('mobile_background_image');
    but don't even see any data pulled when I
    console.log()
    the var, the most I get is null

  3. Wrote my
    .each()
    multiple ways:

    // Attempt #1
    $('.bg-img').each(function() {

    if($(window).width() < 768) {
    var bgUrl = 'url("' + php_vars.mobile_bg + '") center center no-repeat)'
    var style = {
    'background': bgUrl,
    'background-size': 'cover'
    }
    $('.bg-img').css(style);
    }

    });

    // Attempt #2
    if($(window).width() < 768) {

    $('.bg-img').each(function() {
    var bgUrl = 'url("' + php_vars.mobile_bg + '") center center no-repeat)'
    var style = {
    'background': bgUrl,
    'background-size': 'cover'
    }

    $('.bg-img').css(style);
    });

    }



Also variations where
$('.bg-img').css(style);
was completely outside the function.

Question(s): For some reason I am not seeing any change when I inspect nor any console errors. How can I properly pull the sub_field data and pass that to and from my functions.php to my scripts.js and once that data is pulled and set in a var is my current function using
.each() if();
etc... correct?

Content-section.php

<?php if( have_rows('section_content') ): ?>
<?php while( have_rows('section_content') ): the_row();
$sectionBG = get_sub_field('background_image');
$sectionContent = get_sub_field('section_text');
?>
<?php if( $sectionBG ): ?>
<div style="background: url('<?php echo $sectionBG ?>') center center no-repeat; background-size: cover;" class="full-height v-center-content bg-img">
<?php endif; ?>
<div class="container animation-element">
<div class="row">
<?php if(get_row_index() % 2 == 0) : ?>
<div class="col-12 col-md-6 offset-md-6 col-xl-5 offset-xl-7">
<?php else : ?>
<div class="col-12 col-md-6 col-xl-5">
<?php endif; ?>
<div class="section-content">
<?php echo $sectionContent ?>
</div>
</div>
</div>
</div>
<?php if( $sectionBG ): ?>
</div>
<?php endif; ?>
<?php endwhile; ?>
<?php endif; ?>


Function.php

wp_enqueue_script('main-js', get_template_directory_uri() . '/js/script.js', array('jquery'), '', true);

wp_localize_script('main-js', 'php_vars', array(
'mobile_bg' => get_sub_field('mobile_background_image')
));
}


Script.js

$('.bg-img').each(function() {

if($(window).width() < 768) {

var bgUrl = 'url("' + php_vars.mobile_bg + '") center center no-repeat)'
var style = {
'background': bgUrl,
'background-size': 'cover'
}

$('.bg-img').css(style);
}

});

Answer Source

After much tinkering I have found a solution that allows me to dynamically pull in the ACF data within a repeater field from my functions php and use in my script.js

The issue was that I was trying to pull the get_sub_field() data without running the has_rows loop, hence why I was receiving no data.

Updated functions.php

$php_vars = array(
    'ajaxurl' => admin_url( 'admin-ajax.php' ),
    'root_dir'  =>  get_template_directory_uri()
);

if (have_rows('section_content')) :
    while (have_rows('section_content')) : the_row();

        $mobile_url[] = get_sub_field('mobile_background_image');

        $php_vars['mobile_bg'] = $mobile_url;
    endwhile;
endif;

print_r($php_vars);

wp_localize_script('main-js', 'php_vars', $php_vars);

Within my functions.php I created a have_loop- more info here - to check if I have the repeater field on the page, if so, set the mobile image url(s) as an array. After that, I create a multidimensional array and add that to my $php_vars.


Updated script.js

if ($(window).width() < 768) {

    var bgIMG = php_vars.mobile_bg;
    var i;

    console.log(bgIMG);

    for ( i = 0; i < bgIMG.length; i++) {
        $('.bg-img').attr('style', 'background: url("'+ bgIMG[i] +'") center center no-repeat; background-size: cover;');
    }

} 

After successfully testing that the url(s) were being stored as an array via print_r($php_vars); I'm able to called that data into my script and storing it into a var bgIMG. Testing to see if the data is still intact using console.log(bgIMG), I create a for loop to to add the data into my background url and increment.


This is the solution I figured out that seems to work. If anyone has a better solution or advice on how to improve this, I'm all ears.