WordPress responsive images

To create responsive images and enable thumbnails in your theme you need to edit a couple of files .The featured image (thumbnail) on this post uses a custom size and is responsive.

The  post’s featured image is used to create a full width banner at the top of a single post.

functions.php

Add the code below to the functions file in  your theme. This may already be there.

 add_theme_support('post-thumbnails'); 

Create a new image size

Use the add-image-size() function. The first parameter is the slug or name of the custom image, the second parameter is the width, the third parameter is the height. The last parameter sets hard crop to true.

// set banner image size 
add_image_size('banner-image', 1600, 600, true);

CSS

In your themes CSS file add the following code, this makes the image responsive.

  img{
    max-width: 100%;
    height: auto;
  }

HTML

In you themes template file, index.php or single.php, add the code below to display the featured image, use the name you created earlier as the function parameter. This should be inside the WordPress loop.




<div class="thumbnail"><?php the_post_thumbnail('banner-image'); ?></div>



There is an example WordPress loop below.

	
<div>
		<?php if( has_post_thumbnail() ): ?>
		
			
<div>
           

Written by <?php $author = get_the_author(); echo $author?> 

 
         
				
<div class="thumbnail"><?php the_post_thumbnail('banner-image'); ?></div>

			</div>

			
<div>
				<?php the_content(); ?>
			</div>

		
		<?php else: ?>
		
			
<div>
				<?php the_content(); ?>
			</div>

		
		<?php endif; ?>
	</div>

Leave a Reply

Your email address will not be published. Required fields are marked *