【问题标题】:Is there a function to get the caption for an image in wordpress有没有在wordpress中获取图像标题的功能
【发布时间】:2026-02-16 07:35:01
【问题描述】:

我正在尝试从 Wordpress 中的图像中获取标题,但我找不到一个简单的函数来获取这些信息。

有人知道怎么弄这个吗?

谢谢

【问题讨论】:

    标签: wordpress image captions


    【解决方案1】:

    如果您想在帖子中获取标题,您可以在“the_post_thumbnail”标签中回显它。

    <?php the_post_thumbnail();
    echo get_post(get_post_thumbnail_id())->post_excerpt; ?>
    

    您也可以使用相同的方法来显示图像描述。这是 WordPress 3.5 中一个更好的功能

    <?php the_post_thumbnail();
    echo get_post(get_post_thumbnail_id())->post_content; ?>
    

    如果您需要设置标题或描述的样式,可以将其包装在如下 div 中。

    <?php the_post_thumbnail();
        echo '<div class="myDiv">' . get_post(get_post_thumbnail_id())->post_excerpt . '</div>'
    ; ?>
    

    希望对您有所帮助。

    【讨论】:

      【解决方案2】:

      原来字幕存储为帖子摘录。所以,

      <?php echo $post->post_excerpt; ?>
      

      如果您在附件图像页面(主题中的 image.php)和循环内,将打印出标题。

      【讨论】:

        【解决方案3】:

        使用 Wordpress 4.8,这个小家伙为我工作:

        <?php the_post_thumbnail_caption(); ?>
        

        【讨论】:

          【解决方案4】:

          我正在使用此代码,它工作正常。

          $get_description = get_post(get_post_thumbnail_id())->post_excerpt; if(!empty($get_description)){//If description is not empty show the div    echo '<div class="img-caption">' . $get_description . '</div>'; }
          

          【讨论】:

            【解决方案5】:

            把这个放在你的 single.php 文件的 figure 标签内

            $image_caption = get_post(get_post_thumbnail_id())->post_excerpt;
            if(!empty($image_caption)) { 
                echo '<figcaption itemprop="caption">' . $image_caption . '</figcaption>'; 
            }
            

            【讨论】: