如何获得WP画廊图像标题?

nix*_*333 4 php wordpress image gallery

我正试图抓住画廊图像,并通过循环获取帖子的信息.所有我得到的图像来源,但不是字幕.这是我的代码

<?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;
?>
Run Code Online (Sandbox Code Playgroud)

使用这个循环我只是在帖子中获得画廊图像的来源.但我也想抓住图片标题.

dan*_*ild 6

在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
    );
}
Run Code Online (Sandbox Code Playgroud)

然后你可以传入id并抓住你需要的任何元数:

attachment_meta = wp_get_attachment(your_attachment_id);
Run Code Online (Sandbox Code Playgroud)

然后循环遍历数组值或简单地引用您想要的键名称(即:标题,描述等):

echo $attachment_meta['caption'];
Run Code Online (Sandbox Code Playgroud)

以上将回应图像的标题.

幸得卢克Mlsna和sporkme这一点.