admin管理员组文章数量:1315336
I have multiple images in WordPress post, each image has different caption. I want to get the image caption by the image index, but I can't figure out how to print the caption.
Here is what I have tried:
//$index - index of the image (if index is 0, its first image)
function getImageCaption($postID, $index){
$post_id = $postID;
// get the post object
$post = get_post( $post_id );
// get the post thumbnail ID
$thumbnail_id = get_post_thumbnail_id($post->ID);
// we need just the content
$thumbnail_image = get_posts(array('p' => $thumbnail_id, 'post_type' => 'attachment'));
if ($thumbnail_image && isset($thumbnail_image[$index])) {
return $thumbnail_image[$index]->post_excerpt;
} else {
return;
}
}
How can I display image caption by index?
I have multiple images in WordPress post, each image has different caption. I want to get the image caption by the image index, but I can't figure out how to print the caption.
Here is what I have tried:
//$index - index of the image (if index is 0, its first image)
function getImageCaption($postID, $index){
$post_id = $postID;
// get the post object
$post = get_post( $post_id );
// get the post thumbnail ID
$thumbnail_id = get_post_thumbnail_id($post->ID);
// we need just the content
$thumbnail_image = get_posts(array('p' => $thumbnail_id, 'post_type' => 'attachment'));
if ($thumbnail_image && isset($thumbnail_image[$index])) {
return $thumbnail_image[$index]->post_excerpt;
} else {
return;
}
}
How can I display image caption by index?
Share Improve this question asked Nov 19, 2020 at 13:44 YotamYotam 11 bronze badge 5 |1 Answer
Reset to default 0I have used function to extract data inside figcaption tags, and $position is stand for the index of the current image.
function getImageCaption($postID, $position){
$post_id = $postID;
// get the post object
$post = get_post( $post_id );
// we need just the content
$content = $post->post_content;
// we need a expression to match things
$regex = '/<figcaption>(.*)<\/figcaption>/';
// we want all matches
preg_match_all( $regex, $content, $matches );
// reversing the matches array
$matches = array_reverse($matches);
// we've reversed the array, so index 0 returns the result
foreach ($matches as $key => $value) {
return $value[$position];
}
}
本文标签: phpHow to get post image caption by index
版权声明:本文标题:php - How to get post image caption by index 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741976434a2408152.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
get_post
instead ofget_posts
and avoid needing to use an index – Tom J Nowell ♦ Commented Nov 19, 2020 at 14:04get_posts
call retrieves a single post, aka the post thumbnail, it's not retrieving the images in the post, and the caption is stored in the post content not on the attachment. To do what you want to do you need to parse the current posts content, not callget_posts
– Tom J Nowell ♦ Commented Nov 19, 2020 at 14:30