You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在‘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:

Step 1: Find the Plugin's Output Code

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();
Step 2: Modify the Code to Add Titles

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() and esc_attr()/esc_html() to sanitize outputs, which keeps your site secure from XSS vulnerabilities.
  • The aria-label helps with accessibility for screen readers.
  • We added a CSS class (random-post-title) so you can style the title easily.
Step 3: Optional Style the Title with CSS

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 07:31:37