Featured image with category overlay for WordPress
A simple way to make WordPress post layouts a bit cleaner is to move the category label from underneath the post excerpt onto the featured image.
This saves some space and makes it easier to see which category a post belongs to. It only takes two steps: adding a small PHP function and some CSS.
Add the category to the featured image
First, we need to modify the featured image HTML so that WordPress also outputs the post category.
Option A: Add the code to functions.php
-
If you're using a child theme, open its
functions.phpfile and add the following code. -
If you don't have a child theme, I'd recommend creating one first. This way, your changes won't be overwritten when the main theme is updated. Most theme developers provide instructions or a starter child theme.
add_filter( 'post_thumbnail_html','tu_add_category_featured_image' );
function tu_add_category_featured_image( $output ) {
$return = $output;
$cat = get_the_category( get_the_ID() );
if ( isset( $cat ) && ! is_singular() ) {
foreach( $cat as $cat_name ) {
$return .= '
' . $cat_name->name . '
';
}
}
return $return;
}
The function uses the post_thumbnail_html filter to append the post category to the featured image HTML. The is_singular() condition prevents the category label from being added to individual post pages.
Option B: Use the Code Snippets plugin
If you don't want to edit theme files directly, you can use the Code Snippets plugin.
Install the plugin, create a new PHP snippet, paste the code above and activate it.
This is also useful if you want to keep custom PHP code separate from your theme.
Position the category over the image
The PHP function adds the category to the featured image, but we still need to position it properly.
Option A: Add CSS to style.css
- Open style.css inside your child theme and add the following CSS:
.featured-image-category {
position: absolute;
top: 5px;
left: 5px;
text-transform: uppercase;
font-weight: bold;
background: rgba(177, 168, 218, 0.8);
color: black;
padding: 3px 25px;
}
You can adjust the top and left values to change the position of the category label, as well as the background colour, transparency and padding.
Make sure the featured image container has position: relative so that the label is positioned relative to the image rather than the page.
Option B: Use Additional CSS
Alternatively, if you don't have access to your theme files, you can add the CSS through the WordPress Customizer.
-
Go to Appearance → Customize → Additional CSS
-
Paste the CSS and publish your changes.
That's it! Your post category should now appear as an overlay on the featured image instead of taking up space underneath the excerpt.