我正试图通过循环抓取图库图片和帖子的信息。所有我得到的图像来源,但不是字幕。这是我的代码
<?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;
?>
使用这个循环我只是在帖子中获得画廊图像的来源。但我也想抓住图片标题。
答案 0 :(得分:6)
找到解决方案on wordpress.org:
坚持你的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。
答案 1 :(得分:4)
wp_prepare_attachment_for_js函数非常适合这类事情。它会返回一小部分关于附件的信息,我认为我们需要的一切。
这里原始代码剪切替换为使字幕可用的代码。在这种情况下,我已将标题放在alt标记中:
<?php
/* The loop */
while ( have_posts() ) :
the_post();
if ( get_post_gallery() ) :
$gallery = get_post_gallery( get_the_ID(), false );
/* create an array of IDs from */
$gids = explode( ",", $gallery['ids'] );
/* Loop through all the image and output them one by one */
foreach ($gids as $id) {
/* pull all the available attachment data with the new function */
$attachment = wp_prepare_attachment_for_js($id);
/* Uncomment the next line to see all the available data in $attachment */
//var_dump($attachment);
/* pick and choose which bits are needed */
?>
<img src="<?php echo $attachment['sizes']['thumbnail']['url']; ?>" class="my-custom-class" alt="<?php echo $attachment['caption']; ?>" />
<?php
}
endif;
endwhile;
?>
值得注意的是,此功能也会返回所有可用的图片尺寸,因此在使用custom image sizes和srcset的组合图片进行响应式图像解决方案时可能会很棒:)
答案 2 :(得分:1)
而是传递get_the_ID只传递整个$ post并使用类似这样的代码
$gallery = get_post_gallery( $post, false );
$gids = explode( ",", $gallery['ids'] );
foreach( $gids as $id ) {
// here you can use the $id to fetch any details of image like below and many more
wp_get_attachment_url( $id );
wp_get_attachment_metadata( $id );
}
您可以尝试打印这些功能的值,并根据您的要求使用它