Saturday, May 16, 2015

Bootstrap Cheat Code for WordPress Thumbnail Mobile Responsiveness

Using the_post_thumbnail() in a WordPress loop displays the post featured image as a thumbnail to the post article. The first parameter size lets setting or customizing the width and height dimensions for the thumbnail. However, I wanted a flexibility for my Bootstrap based WordPress theme wherein the post thumbnail will display in a smaller size in mobile. In short, I wanted a post thumbnail mobile responsiveness on its display. The WordPress loop uses a Media Object to display the title, time posted, excerpt and of course, the thumbnail. A sample loop is shown below:
The Media Object calls the_post_thumbnail() while passing the 'thumbnail' parameter. The 'thumbnail' size is set to 150x150:

When the theme is rendered, WordPress set the width and height attributes to 150. I could have used CSS3's media query, but was not sure is it could have overwritten the width and height attributes. I decided come up with my own cheat code to display the thumbnail in a different size on mobiles:
The cheat involves using two image links. The first image link passes 'thumbnail' as the size parameter. The classes "hidden-xs hidden-sm" makes sure that the image will not display on mobile sized devices. This makes sure that the image is displayed in traditional desktop or laptop computers. The second image link passes array(50,50) as the size parameter. The thumbnail is displayed in 50px width and height. The classes "hidden-md hidden-lg" makes sure that the image will not display on computers with medium or large screens, i.e. desktop or laptop computers. This makes sure that the image is displayed on mobile devices. The WordPress loop code with the Bootstrap cheat is listed below
<?php 
if(have_posts()): 
while (have_posts()): the_post(); 
?>
<div class="media">
 <a href="#" class="pull-left hidden-xs hidden-sm">
  <?php the_post_thumbnail('thumbnail', array( 'class' => 'media-object img-rounded' )); ?>
 </a>
 <a href="#" class="pull-left hidden-md hidden-lg">
  <?php the_post_thumbnail(array(50,50), array( 'class' => 'media-object img-rounded' )); ?>
 </a>
 <div class="media-body">
  <h4 class="media-heading"><?php the_title(); ?> <small>Posted on<?php the_time('F j, Y'); ?></small></h4>
  <p><small><?php echo(get_the_excerpt()); ?></small></p>
  <p><a href="<?php the_permalink(); ?>" class="btn btn-primary">Read More</a>
  </p>
 </div>
</div>
<?php endwhile; ?>
<?php else: ?>
<?php endif; ?>

No comments:

Post a Comment