get_post_gallery_images()
云策文档标注
概述
get_post_gallery_images() 函数用于检查文章内容中的图库,并返回第一个找到的图库的图像 src 数组。它基于 get_post_gallery() 实现,适用于 WordPress 开发者快速获取图库图片链接。
关键要点
- 函数检查指定文章内容中的图库,返回第一个图库的图像 src 数组
- 参数 $post 可选,可以是文章 ID 或 WP_Post 对象,默认为全局 $post
- 返回值为字符串数组,按顺序列出图库图像的 src
- 在 WordPress 3.6.0 版本中引入
- 注意:如果图库类型设置为 'slideshow',函数可能无法正常工作,需要从短代码中移除 type="slideshow"
代码示例
add_filter( 'the_content', 'wpdocs_show_gallery_image_urls' );
/**
* Show image URLs below the content
*/
function wpdocs_show_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 the first gallery in the post
$gallery = get_post_gallery_images( $post );
$image_list = '';
// Loop through each image in each gallery
foreach( $gallery as $image_url ) {
$image_list .= '' . '' . '';
}
$image_list .= '';
// Append our image list to the content of our post
$content .= $image_list;
return $content;
}注意事项
- 函数不适用于 type="slideshow" 的图库短代码,需要移除该属性才能正常获取图像
原文内容
Checks a post’s content for galleries and return the image srcs for the first found gallery.
Description
See also
Parameters
Source
function get_post_gallery_images( $post = 0 ) {
$gallery = get_post_gallery( $post, false );
return empty( $gallery['src'] ) ? array() : $gallery['src'];
}
Changelog
| Version | Description |
|---|---|
| 3.6.0 | Introduced. |
Skip to note 3 content
Codex
Example
A simple example of how to append the raw image URLs to the content of any post or page that has at least one gallery.
add_filter( 'the_content', 'wpdocs_show_gallery_image_urls' ); /** * Show image URLs below the content */ function wpdocs_show_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 the first gallery in the post $gallery = get_post_gallery_images( $post ); $image_list = '<ul>'; // Loop through each image in each gallery foreach( $gallery as $image_url ) { $image_list .= '<li>' . '<img src="' . $image_url . '">' . '</li>'; } $image_list .= '</ul>'; // Append our image list to the content of our post $content .= $image_list; return $content; }Skip to note 4 content
MaFt
This does not work if the gallery type is set to ‘slideshow’. It returns nothing. Removing type=”slideshow” from the gallery shortcode allows the images to be picked up by this function.