如何在‘display random posts’插件代码中添加特色图片下方的文章标题?
Alright, let's get your random posts showing both featured images and their titles below—super straightforward once you know where to tweak the code. Here's what you need to do:
First, open up your "display random posts" plugin files (usually in /wp-content/plugins/display-random-posts/). Look for the file that handles front-end output—this might be the main display-random-posts.php file, or a dedicated template file like templates/random-posts.php.
Search for code that loops through random posts and outputs the featured image. It’ll look something like this:
foreach( $random_posts as $post ) { setup_postdata( $post ); // This line outputs just the featured image echo get_the_post_thumbnail( $post->ID, 'thumbnail' ); } wp_reset_postdata();
Update that loop to include the post title (wrapped in a link to the post, which is better for user experience). Here’s the revised code:
foreach( $random_posts as $post ) { setup_postdata( $post ); // Wrap the featured image in a link to the post (optional but recommended) echo '<a href="' . esc_url( get_permalink( $post->ID ) ) . '" aria-label="' . esc_attr( get_the_title( $post->ID ) ) . '">'; echo get_the_post_thumbnail( $post->ID, 'thumbnail' ); echo '</a>'; // Add the post title below the image, also linked echo '<h3 class="random-post-title"><a href="' . esc_url( get_permalink( $post->ID ) ) . '">' . esc_html( get_the_title( $post->ID ) ) . '</a></h3>'; } wp_reset_postdata();
A few quick notes:
- We use
esc_url()andesc_attr()/esc_html()to sanitize outputs, which keeps your site secure from XSS vulnerabilities. - The
aria-labelhelps with accessibility for screen readers. - We added a CSS class (
random-post-title) so you can style the title easily.
If you want to make the title look polished, add this CSS to your theme’s custom CSS section (Appearance > Customize > Additional CSS):
.random-post-title { margin: 8px 0 16px; font-size: 1rem; line-height: 1.4; text-align: center; /* Center-align the title if you want */ } .random-post-title a { color: #333; text-decoration: none; } .random-post-title a:hover { text-decoration: underline; }
That’s it! Now your random posts will display the featured image with the post title directly below it.
内容的提问来源于stack exchange,提问作者Nish B

