简体   繁体   中英

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);
    }

}); 

This is the role of CSS media queries. In your main style sheet you would have

background-image: url('pic1.jpg');

In your mobile css file you would have

background-image: url('pic2.jpg');

In your html you would have

<link rel="stylesheet" href="style.css" type="text/css">
<link rel="stylesheet" href='mobile.css" type="text/css" media="only screen and (max-device-width:768px)">
$(window).on('resize', function () {
   if($(this).width() < 768)
   {
     ('.bg-img').each(function() {
        var bgUrl = 'url("' + php_vars.mobile_bg + '") center center no-repeat)'
        var style = {'background': bgUrl,
                     'background-size': 'cover'};
        $(this).css(style);
      });
    }
});

This question might be old - but you can just install the mobble plugin - this tells you what kind of device in on you page - it also adds a class for the body.

Then you can simply use the plugins core functions -

<?php
//is_handheld(); // any handheld device (phone, tablet, Nintendo)
//is_mobile(); // any type of mobile phone (iPhone, Android, etc)
//is_tablet(); // any tablet device
//is_ios(); // any Apple device (iPhone, iPad, iPod)
/*is_iphone();
//is_ipad();
//is_ipod();
//is_android();
//is_blackberry();
//is_opera_mobile();
//is_symbian();
//is_kindle();
//is_windows_mobile();
//is_motorola();
//is_samsung();
//is_samsung_tablet();
//is_sony_ericsson();
//is_nintendo(); */

if(is_mobile()) {
    $bgURL = get_sub_field("your mobile image here"); 
} else {
    $bgURL = get_sub_field("your desktop image here");
}

Read more about the plugins functions and download here : https://wordpress.org/plugins/mobble/

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM