【问题标题】:Wordpress get attachment image captionWordpress 获取附件图片标题
【发布时间】:2021-09-04 02:52:15
【问题描述】:

我尝试将附件元标题值设为mentioned here,但无法获得任何输出。 [created_timestamp] 或 [iso] 等其他元数组给出了它们的值。

$img_meta = wp_get_attachment_metadata( $id );
echo $img_meta[image_meta][caption];

[标题] 和 [标题] 都会出现此问题。非常感谢任何帮助。

【问题讨论】:

  • 可能该值只是空的,或者该值根本不存在。无论如何尝试“print_r($img_meta)”这应该显示整个数组的键和值。
  • 这是图片中的图像元数据,而不是来自 WordPress - 所以看起来您的图像在拍摄时没有应用该元数据。与您实际上链接的 codex 页面上的示例相同。
  • @SimonPollard 当然,我确实为使用的图像输入了这些值。
  • @IhabAbdel-Rahim 你在哪里输入了这些值?
  • @PeterM 正如我所提到的, print_r($img_meta) 为标题和标题提供了空值,即使使用的图像也输入了这些值。

标签: php wordpress


【解决方案1】:

您希望从 wp_get_attachment_metadata 获取的标题和标题不是您在 WordPress 中添加的标题和标题,它们是来自实际图像本身的元数据。要获取 WordPress 数据,请使用类似这样的方法(假设 $id 是图像的 id)。

$image = get_post($id);
$image_title = $image->post_title;
$image_caption = $image->post_excerpt;

【讨论】:

  • 你能分享一下参考页面吗?
  • wordpress.org/support/topic/… 的确切代码 - 主要是 wp_get_attachment_metadata 没有得到你需要的东西,虽然我知道你为什么要使用它,但这个名字很混乱:)
  • 我已经用新代码更新了我的答案 - 并进行了测试。这应该有效。
  • 很高兴听到 @IhabAbdel-Rahim :)
  • 在 Wordpress 4.8.1 上运行良好
【解决方案2】:

从 WordPress 4.6.0 开始,get_the_post_thumbnail_caption($post) 可以为您获取指定帖子的标题。

【讨论】:

  • 你可以通过 $post 来获取具体值
【解决方案3】:

把它放在你的functions.php文件中:

function show_caption_image($type='title'){
  global $post;
    $args = array( 'post_type' => 'attachment', 'orderby' => 'menu_order', 'order' => 'ASC', 'post_mime_type' => 'image' ,'post_status' => null, 'numberposts' => null, 'post_parent' => $post->ID );

    $attachments = get_posts($args);
    if ($attachments) {
        foreach ( $attachments as $attachment ) {
      $alt = get_post_meta($attachment->ID, '_wp_attachment_image_alt', true);
      $image_title = $attachment->post_title;
      $caption = $attachment->post_excerpt;
      $description = $image->post_content;
    }
  }  
  return $type == 'title' ? $image_title : $caption.$description;
}

在您的主题中的图像下方,或者您喜欢放置它的任何位置,通常在 single.php 文件中:

<?php if ( has_post_thumbnail() ) : 
        ?>
      <span class="image main"><img src="<?php echo get_the_post_thumbnail_url()?>" alt="<?php echo get_the_title()?>" /><i><?php echo show_caption_image();?></i></span>
      <?php endif; ?> 

【讨论】:

    猜你喜欢
    • 2014-06-03
    • 1970-01-01
    • 2019-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-16
    相关资源
    最近更新 更多