I’d like to be able to able to swap an img’s src value with a variable created in PHP.

I currently am using javascript to determine the device width. This is happening within the .php file containing the WordPress loop. Upon recognizing the device width, I would like to change the img’s src value accordingly.

I can successfully retrieve the PHP variables using this JS function however only when the function is written in the loop, and as you all know, this will duplicate the function for each post and is resulting in an error.

I need to be able to calculate these given PHP variables outside the loop and then inject them into the img src value inside the loop.

I recognize I may have more errors in this code than what I am looking to resolve! I have been working on this for some time and this particular issue has become quite troubling. Thanks in advance.

Current Code in Use:

<?php query_posts( array ( 'home' => 'WordPress Themes', 'orderby' => 'rand', 'posts_per_page' => -1 ) ); ?>
<?php while ( have_posts() ) : the_post(); ?>
  <script>
    function getImagePath(){
      if (window.matchMedia('(max-device-width: 1920px)').matches) {
        var theSizedImage = <?php the_field('desktop_image'); ?>
      }if (window.matchMedia('(max-device-width: 1280px)').matches) {
        var theSizedImage = <?php the_field('tablet_image'); ?>
      }if (window.matchMedia('(max-device-width: 600px)').matches) {
        var theSizedImage = <?php the_field('mobile_image'); ?>
      }
      return theSizedImage;
    } 
   </script>
   <img src="pixel.gif" onload="this.onload=null; this.src=getImagePath();"  />
<?php endwhile;
wp_reset_query();
?>

Read more here: Replacing Image Source Value With a PHP Variable Based on Device Width


Solution:

If you know the solution of this issue, please leave us a reply in Comment section, to update the question.

Related Wordpress search:

, , , , , , ,

Wordpress related questions and answers: