Episode 28 of 32
Styling the Star Ratings
Create a beautiful star rating display using CSS — from the custom field value to a polished visual component.
Styling the Star Ratings
In the previous episodes, we added a star_rating custom field and displayed it with text stars (★/☆). Now let's create a polished, professional star rating component with CSS.
The PHP Output
<?php
$rating = get_post_meta(get_the_ID(), 'star_rating', true);
if ($rating) : ?>
<div class="star-rating" data-rating="<?php echo esc_attr($rating); ?>">
<?php for ($i = 1; $i <= 5; $i++) : ?>
<span class="star <?php echo ($i <= $rating) ? 'filled' : 'empty'; ?>">★</span>
<?php endfor; ?>
<span class="rating-text"><?php echo $rating; ?>/5</span>
</div>
<?php endif; ?>
CSS Styling
.star-rating {
display: inline-flex;
align-items: center;
gap: 2px;
margin: 8px 0;
}
.star-rating .star {
font-size: 20px;
transition: color 0.2s ease;
}
.star-rating .star.filled {
color: #f5a623;
text-shadow: 0 0 4px rgba(245, 166, 35, 0.3);
}
.star-rating .star.empty {
color: #ddd;
}
.star-rating .rating-text {
margin-left: 8px;
font-size: 13px;
font-weight: 600;
color: #888;
}
Adding Half-Star Support
For decimal ratings (e.g., 3.5), update the PHP:
<?php
$rating = floatval(get_post_meta(get_the_ID(), 'star_rating', true));
if ($rating) : ?>
<div class="star-rating">
<?php for ($i = 1; $i <= 5; $i++) :
if ($i <= floor($rating)) :
$class = 'filled';
elseif ($i == ceil($rating) && fmod($rating, 1) != 0) :
$class = 'half';
else :
$class = 'empty';
endif;
?>
<span class="star <?php echo $class; ?>">★</span>
<?php endfor; ?>
<span class="rating-text"><?php echo $rating; ?>/5</span>
</div>
<?php endif; ?>
Half-Star CSS
.star-rating .star.half {
position: relative;
color: #ddd;
}
.star-rating .star.half::before {
content: '★';
position: absolute;
left: 0;
top: 0;
width: 50%;
overflow: hidden;
color: #f5a623;
}
Star Rating Variations
| Variation | CSS Property |
|---|---|
| Larger stars | font-size: 28px |
| Different colors | color: #e74c3c (red) |
| Glow effect | text-shadow: 0 0 8px rgba(245,166,35,0.5) |
| Spaced out | gap: 4px or letter-spacing: 4px |
Integrating in Post Cards
.post-card .star-rating {
margin-top: auto;
padding-top: 10px;
border-top: 1px solid #f0f0f0;
}
/* Make card body flex column for bottom alignment */
.post-card-body {
display: flex;
flex-direction: column;
height: 100%;
}
Key Takeaways
- The star rating combines PHP (logic) and CSS (styling) for a polished component
- Use the
.filledand.emptyclasses for full-star display - Half-star support uses a
::beforepseudo-element withoverflow: hiddenat 50% width - Gold color (
#f5a623) with subtle text-shadow creates a professional look - Always use
esc_attr()when outputting custom field values in HTML attributes