如何获取 WP 图库图片标题?
·
问题:如何获取 WP 图库图片标题?
我正在尝试通过循环获取图库图像,它是帖子的信息。我得到的只是图片来源,而不是字幕。这是我的代码
<?php
/* The loop */
while ( have_posts() ) :
the_post();
if ( get_post_gallery() ) :
$gallery = get_post_gallery( get_the_ID(), false );
/* Loop through all the image and output them one by one */
foreach( $gallery['src'] AS $src ) {
?>
<img src="<?php echo $src; ?>" class="my-custom-class" alt="Gallery image" />
<?php
}
endif;
endwhile;
?>
使用这个循环,我只能在帖子中获取画廊图像的来源。但我也想获取图片说明。
解答
在 wordpress.org](https://wordpress.org/ideas/topic/functions-to-get-an-attachments-caption-title-alt-description)上找到了解决方案[:
把它放在你的functions.php中:
function wp_get_attachment( $attachment_id ) {
$attachment = get_post( $attachment_id );
return array(
'alt' => get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true ),
'caption' => $attachment->post_excerpt,
'description' => $attachment->post_content,
'href' => get_permalink( $attachment->ID ),
'src' => $attachment->guid,
'title' => $attachment->post_title
);
}
然后你可以传入 id 并获取你需要的任何元数据,如下所示:
attachment_meta = wp_get_attachment(your_attachment_id);
然后要么循环遍历数组值,要么简单地通过你想要的键名引用(即:标题、描述等):
echo $attachment_meta['caption'];
以上将呼应图像的标题。
这要归功于Luke Mlsna和sporkme。
更多推荐
所有评论(0)