PHP Echoing file/link location

I’m trying to accomplish this:

If the device is not mobile, then post the slider. If it is mobile, then post an image. I’m trying to convert this code:

  <div class="container">
        <div class="hero">
            <?php if(get_field('slider')): while(has_sub_field('slider')): $x++; ?>
            <div class="slide">
                <div class="copy">
                    <?php the_sub_field('slide_copy'); ?>
                    <a href="<?php the_sub_field('link'); ?>">Learn More</a>
                </div>
                <img src="<?php the_sub_field('image'); ?>" width="1280" height="635" alt="" class="img-responsive">
            </div>   
            <?php endwhile; endif; ?>
        </div>
    </div>

and have gotten this far:

<div class="container">
    <div class="hero">
     <?php if ( !wp_is_mobile() ) {
        if (get_field('slider')): while(has_sub_field('slider')): $x++;
        echo'<div class="slide">';
        echo'<div class="copy">';
          the_sub_field('slide_copy');
        echo'<a href="' . the_sub_field('link') . '">Learn More</a>';
        echo'</div>';
        echo'<img src="' . the_sub_field('image') . '" width="1280" height="635" alt="" class="img-responsive">';
        echo'</div>';
        endwhile;
        endif;
     } else {
         echo'<div class="headimg"><img src="">This is the mobile image</div>';
     }
     ?>
    </div>

Okay. I figured it out: replace ‘the_sub_field’ with ‘get_sub_field’. Reference: use get_sub_field() in loops instead of the_sub_field(). the difference is get_sub_field() return the value as a string, and the_sub_field() print the data.

<div class="container">
    <div class="hero">
     <?php if ( !wp_is_mobile() ) {
        if (get_field('slider')): while(has_sub_field('slider')): $x++;
        echo'<div class="slide">';
        echo'<div class="copy">';
          the_sub_field('slide_copy');
        echo'<a href="' . get_sub_field('link') . '">Learn More</a>';
        echo'</div>';
        echo'<img src="' . get_sub_field('image') . '" width="1280" height="635" alt="" class="img-responsive">';
        echo'</div>';
        endwhile;
        endif;
     } else {
         echo'<div class="headimg"><img src="">This is the mobile image</div>';
     }
     ?>
    </div>
</div>
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.