Code Snippet: Using a featured image as a background in WordPress

by on July 25, 2016

Code Snippet: Using a featured image as a background in WordPress

  •  
  •  
  •  
  •  

Of course if you want to have a background to a div it’s generally correct to set that with a separate stylesheet. But in WordPress if you want it to be dynamic so that whatever the person publishing a post sets as the featured image it comes up as the background to a div you can do this inline and with PHP like so:

 


<?php global $post; ?>
<?php
$src = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), array( 5600,1000 ), false, '' );
?>
<div style="background: url(<?php echo $src[0]; ?> ) !important;">text </div>

 

I hope all who needed to know how to use a featured image as a background in WordPress found what they needed! Thanks for reading!


  •  
  •  
  •  
  •  

Download my E-book "WordPress Development for Noobs" for free right now:

  • This field is for validation purposes and should be left unchanged.
Only the best of web design & marketing

Ready to get started?

Get a free consultation now