Search code examples
wordpressloopsfooter

Get wordpress featured image URL into a footer script


Is there a way to pull an image url from a query, and have that url echoed into a plugin script that's in the footer of the same page? My problem is that I have a layerslider that needs a static background image. The problem is that the query is ran at the top of the page, so I lose access to the loop by the time the javascript is called in the footer.

I have this query, INSIDE of the normal page loop:

/*Normal Page Loop Here*/ 
if (have_posts()) : while (have_posts()) : the_post();

/*Begin Secondary Query to be Inserted into this page*/
$args = array(
'post_type' => 'projects',
'orderby' => 'rand',
'posts_per_page' => 1,
'meta_query' => array(
           array(
            'key' => 'custom_featured',
            'value' => 'on',
            )
        )
);
$my_query = new WP_Query($args);


    /*Output Results of Internal Page Query*/
if( $my_query->have_posts() ) {
  while ($my_query->have_posts()) : $my_query->the_post(); ?>
       the_title();
       the_post_thumbnail('i-need-this-url-in-the-footer-script');        

    endwhile;/*End the secondary query loop*/
    wp_reset_query();


endwhile; endif;/*End the page loop*/    

I essentially need the URL of the featured image of this new WP_Query inserted into the script that's in the footer:

<script type="text/javascript">
    //Layer Slider
       $(document).ready(function(){
       $('#layerslider').layerSlider({
       globalBGImage: '<?php echo $imagefromloopurlhere; ?>'
     });
  });
</script>

Solution

  • This will get the URL of the image

    $image_src = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'thumbnail_size' );  
    if($image_src)
         echo $image_src[0];
    

    In order to place the variable into the footer you could do something like this:

    global $project_featured_url;
    while ($my_query->have_posts()) : $my_query->the_post();
       the_title();
       $image_src = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'thumbnail_size' );  
       if($image_src)
          $project_featured_url = $image_src[0];
       else
           $project_featured_url = 'some default url to avoid javascript error';
    endwhile;/*End the secondary query loop*/
    

    Then in your footer

    <?php global $project_featured_url; ?>
    <script type="text/javascript">
        //Layer Slider
           $(document).ready(function(){
           $('#layerslider').layerSlider({
           globalBGImage: '<?php echo $project_featured_url; ?>'
         });
      });
    </script>