我有这个代码来检索图库中图像的图像网址,它工作正常,但我无法弄清楚如何获取每个图像的标题。
我尝试了搜索,但我似乎无法将所有信息放在一起!关于我如何找回字幕的任何建议?
function show_related_gallery_image_urls( $content ) {
global $post;
// Only do this on singular items
if( ! is_singular() )
return $content;
// Make sure the post has a gallery in it
if( ! has_shortcode( $post->post_content, 'gallery' ) )
return $content;
// Retrieve all galleries of this post
$galleries = get_post_galleries_images( $post );
$image_list = <<<END
<div class="side_bar">
<div class="related">
<h3>Related Images</h3>
END;
// Loop through all galleries found
foreach( $galleries as $gallery ) {
// Loop through each image in each gallery
foreach( $gallery as $image ) {
$src = $image;
$image_list .= '<a href="' . $src . '" rel="' . get_the_title() . '">'
. '<img src="' . $src .'" />'
. '</a>';
}
}
$image_list .= '</div></div>';
// Append our image list to the content of our post
$content .= $image_list;
return $content;
}
add_filter( 'the_content', 'show_related_gallery_image_urls' );
我希望我能很好地解释自己!谢谢!
答案 0 :(得分:0)
这还没有通过尝试来测试,我稍微清理了一些代码:
1)将前两个IF语句合并为1
2)使用get_post_gallery()
(Codex)返回src
和图片ID
。我们使用图片ID来返回标题,如果需要,我们也可以获得更多描述。
3)删除了包含的Foreach语句,因为我的方法只返回1个库,而不是多个,所以不需要循环。
function show_related_gallery_image_urls( $content ) {
global $post;
// Only do this on singular items
if( ! is_singular() || !has_shortcode( $post->post_content, 'gallery' ) )
return $content;
// Retrieve all galleries of this post
$galleries = get_post_gallery( $post, false );
$image_list = <<<END
<div class="side_bar">
<div class="related">
<h3>Related Images</h3>
END;
// Loop through each image in each gallery
$i = 0; // Iterator
foreach( $gallery['src'] as $src ) {
$caption = wp_get_attachment($gallery['id'][$i])['caption'];
$image_list .= '<a href="' . $src . '" rel="' . get_the_title() . '">'
. '<img src="' . $src .'" />'
. '<div class="caption">'
. $caption
. '</div>'
. '</a>';
$i++; // Incremenet Interator
}
$image_list .= '</div></div>';
// Append our image list to the content of our post
$content .= $image_list;
return $content;
}
add_filter( 'the_content', 'show_related_gallery_image_urls' );
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
);
}
在旁注中,有一个图库过滤功能,您可以在其中更改图库的显示方式post_gallery Filter,here's a question显示如何编辑图库。还有一个很棒的WordPress Stack Exchange,这可能对将来有所帮助!