title: WordPress PHP if no gallery image, use featured image
body: <p>Using WordPress, I have a gallery and featured image on my custom posttype, at the bottom of the page is a section that shows all of the other posts under the custom posttype.</p>
  
  <p>I'm trying to bring back the first gallery image from the post, if there isn't a gallery image then the featured image should be used, but only the gallery image is being brought back.</p>
  
  <p>Here is my code below:</p>
  
  <pre><code>&lt;div class="container"&gt;
      &lt;?php
      $args = array(
          'post_type' =&gt; 'service',
          'post_status' =&gt; 'publish',
          'order'    =&gt; 'ASC'
      );
      $query = new WP_Query( $args );
      $count = 0;
      echo '&lt;div class="row"&gt;';
      while($query -&gt; have_posts()) : $query -&gt; the_post();
      $featuredimage = wp_get_attachment_image_src( get_post_thumbnail_id( $thePost-&gt;ID ), 'large' );
      $images = get_post_meta($post-&gt;ID, 'vdw_gallery_id', true);
      if($count == 5){
          $count = 0;
          echo '&lt;/div&gt;&lt;div class="row"&gt;';
      };
      ?&gt;
      &lt;div class="col- col-md service-images"&gt;
          &lt;a href="&lt;?php echo get_the_excerpt(); ?&gt;"&gt;
              &lt;?php foreach ($images as $image) {
                  $img = wp_get_attachment_image_src($image, 'large');
                  if ( empty( $img ) ) {
                      if ($img === 0) {
                          echo '&lt;div class="images" style="background:linear-gradient(rgba(0, 0 ,0, 0.1), rgba(0, 0, 0, 0.1)), url(' . $featuredimage[0] . ') background-position: center; background-size: cover; background-repeat: no-repeat; height: 100%;"&gt;';
                      }
                  }
                  else {
                      echo '&lt;div class="images" style="background:linear-gradient(rgba(0, 0 ,0, 0.1), rgba(0, 0, 0, 0.1)), url(' . $img[0] . '); background-position: center; background-size: cover; background-repeat: no-repeat; height: 100%;"&gt;';
                  }; ?&gt;
                  &lt;div class="overlay"&gt;
                      &lt;div class="col- col-md service-block-title"&gt;
                          &lt;h3&gt;&lt;?php echo the_title(); ?&gt;&lt;/h3&gt;
                      &lt;/div&gt;
                  &lt;/div&gt;
                  &lt;?php }; ?&gt;
          &lt;/a&gt;
      &lt;/div&gt;
  &lt;/div&gt;
  &lt;?php $count++;
  endwhile;
  echo '&lt;/div&gt;';?&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>Simply, if $img is empty (no image in the gallery) then use $featuredimage.</p>
  
  <p>Can anyone tell me where I'm going wrong? Any help would be greatly appreciated.</p>