WordPress and CSS

Apply a gradient onto a WordPress post_thumbnail picture

You are working on a WordPress custom theme and you want to apply a gradient onto the post_thumbnail picture.

Applying a gradient onto WordPress post_thumbnail is very easy. There are two main steps:

  1. Insert the image in the template file.
  2. Apply CSS properties in the CSS file.

Let’s have a more thorough look at these steps!

Summary

How to display the WordPress post_thumbnail?

First of all, the image must be present: let’s insert it!

Steps to insert the post_thumbnail in the template

  1. Go to the template file where the image must be displayed.
  2. Create the WP loop to get the article data.
  3. The subtilty is you have to insert a <div></div> HTML element tag where you want the image to appear.
  4. Do not forget to give this div a class! And then…
  5. Insert the image via the the_post_thumbnail() function. You can specify a size as shown in the example below.
PHP
<?php if( have_posts() ) : ?>
  <div>
    <?php while( have_posts() ) : the_post();
      <article class=”post-card”>
        <!– picture –>
        <div class=”post-card__picture”>
          <?php the_post_thumbnail(‘medium’) ?>
        </div>
        //… code
      </article>
      endwhile;
    ?>
  </div>

Nothing more to do on this file.

How to apply the gradient via CSS properties?

CSS properties to apply to the <div> element the image is inserted in

Apply two important properties to the <div> element to have the possibility to place the gradient then :

    1. position: relative;
    2. width: 100%;

Create the gradient over the post_thumbnail image

  1. Create a pseudo-element ::before which will be automatically placed on top of the post_thumbnail image. Remark: do not forget the content property!
  2. Make this new element fully cover the image with:
    1. position: absolute;
    2. the top, right, bottom and left set to 0;
  3. Apply the gradient to this newly created pseudo-element:
    • background-image: linear-gradient(/* informations about the gradient here */);
CSS
.post-card__picture {
  position: relative;
  width: 100%;
}
.post-card .post-card__picture::before {
  content: ” “;
  position: absolute;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
  background-image: linear-gradient(178.87deg, rgba(9, 57, 84, 0.78) 0.5%, rgba(79, 79, 79, 0.35) 66.87%);
}

In conclusion

To apply a gradient onto a WordPress post_thumbnail picture is easy and fast, once you know exactly what your gradient looks like!

It is better to try some settings on figma or AdobeXD for example before starting to code!

Haut de page