如何在索引循环中显示自定义字段值?含文章评分展示需求
Hey there! Let's get that rating showing up both on your single custom post type pages and the archive/index page for those posts. Here's how to make it work smoothly and keep your code clean:
First, let's wrap your existing rating code into a function so you can call it anywhere—no more copying and pasting the same code twice. Add this to your theme's functions.php file:
function display_post_rating($post_id = null) { // Use the current post's ID if no ID is passed in if (!$post_id) { global $post; $post_id = $post->ID; } // Get the rating value, default to 0 if it doesn't exist $rating = get_post_meta($post_id, 'rating', true); $rating = empty($rating) ? 0 : intval($rating); // Make sure the rating stays between 0 and 5 to avoid weird behavior $rating = max(0, min(5, $rating)); // Print filled stars for ($i = 1; $i <= $rating; $i++) { echo '<i class="fa fa-star"></i>'; } // Print empty stars for ($i = $rating; $i < 5; $i++) { echo '<i class="fa fa-star-o"></i>'; // Uses Font Awesome's empty star icon } }
On your single post template (like single-yourcpt.php, where yourcpt is your custom post type slug), call the function wherever you want the rating to appear—probably at the bottom of the post content:
// Add this where you want the rating to show (e.g., after the post content) <div class="post-rating"> <strong>Rating:</strong> <?php display_post_rating(); ?> </div>
For your archive or index page (like archive-yourcpt.php or a custom loop), call the function inside the post loop so it renders a rating for every post in the list:
<?php if (have_posts()) : ?> <?php while (have_posts()) : the_post(); ?> <!-- Your existing post title/content code here --> <h2><?php the_title(); ?></h2> <div class="post-excerpt"><?php the_excerpt(); ?></div> <!-- Add the rating here --> <div class="post-rating"> <strong>Rating:</strong> <?php display_post_rating(get_the_ID()); ?> <!-- Explicitly pass the post ID (optional but safe) --> </div> <?php endwhile; ?> <?php endif; ?>
- Font Awesome Check: Make sure Font Awesome is loaded on your site—if not, the star icons won't show. You can enqueue it via your theme's
functions.phpor add the CDN link to your header. - Style It Up: Add some CSS to make the stars look nice. For example:
.post-rating { margin: 10px 0; color: #333; } .post-rating .fa-star { color: #ffc107; /* Bright yellow for filled stars */ } .post-rating .fa-star-o { color: #ddd; /* Gray for empty stars */ } - Handle Empty Ratings: The function already defaults to 0 if the
ratingcustom field is missing, so you won't get broken loops or missing stars.
内容的提问来源于stack exchange,提问作者Nisha Ankit

