get_post_gallery()
云策文档标注
概述
get_post_gallery() 函数用于检查指定文章内容中的图库,并返回第一个找到的图库数据。它基于 get_post_galleries() 实现,并提供了一个过滤器钩子以允许自定义输出。
关键要点
- 函数检查文章内容中的图库,返回第一个图库的数据或 HTML。
- 参数 $post 可选,可以是文章 ID 或 WP_Post 对象,默认为全局 $post。
- 参数 $html 可选,布尔值,控制返回 HTML 还是数组数据,默认为 true(返回 HTML)。
- 返回值类型为 string 或 array,取决于 $html 参数设置。
- 如果未找到图库,函数返回 false(布尔值)。
- 提供 apply_filters('get_post_gallery', $gallery, $post, $galleries) 钩子,允许过滤第一个找到的图库。
- 相关函数包括 get_post_galleries() 和 get_post_gallery_images()。
代码示例
// 示例:使用数据输出而非 HTML,自定义图像类
$gallery_data = get_post_gallery( $post_id, false );
if ( $gallery_data && is_array( $gallery_data ) ) {
foreach ( $gallery_data['src'] as $src ) {
echo '<img src="' . esc_url( $src ) . '" class="my-custom-class" alt="Gallery image" />';
}
}注意事项
- 函数在 WordPress 3.6.0 版本中引入。
- 确保正确处理返回值,当无图库时返回 false,需进行类型检查。
- 使用过滤器钩子时,注意参数顺序和类型,以保持兼容性。
原文内容
Checks a specified post’s content for gallery and, if present, return the first
Parameters
Source
function get_post_gallery( $post = 0, $html = true ) {
$galleries = get_post_galleries( $post, $html );
$gallery = reset( $galleries );
/**
* Filters the first-found post gallery.
*
* @since 3.6.0
*
* @param array $gallery The first-found post gallery.
* @param int|WP_Post $post Post ID or object.
* @param array $galleries Associative array of all found post galleries.
*/
return apply_filters( 'get_post_gallery', $gallery, $post, $galleries );
}
Hooks
- apply_filters( ‘get_post_gallery’, array $gallery, int|WP_Post $post, array $galleries )
-
Filters the first-found post gallery.
Changelog
| Version | Description |
|---|---|
| 3.6.0 | Introduced. |
Skip to note 3 content
julien731
If there is no gallery present in the page, the function will return
false(boolean).Skip to note 4 content
Codex
Example
Output each image in a gallery with our own custom image class when using data output and not HTML:
<img src="<?php echo $src; ?>" class="my-custom-class" alt="Gallery image" />Example data output
array (size=3) 'link' => string 'file' (length=4) 'ids' => string '423,424,425,426' (length=15) 'src' => array (size=4) 0 => string 'http://www.yoursite.com/wp-content/uploads/2013/10/1296136694836-150x150.jpg' (length=85) 1 => string 'http://www.yoursite.com/wp-content/uploads/2013/10/1315981706292-150x150.jpg' (length=85) 2 => string 'http://www.yoursite.com/wp-content/uploads/2013/10/fate-stay-night-446-wall1200-150x150.jpg' (length=100) 3 => string 'http://www.yoursite.com/wp-content/uploads/2013/10/GpTq3-150x150.jpg' (length=77)