函数文档

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

$postint|WP_Postoptional
Post ID or WP_Post object. Default is global $post.

Return

string[] A list of a gallery’s image srcs in order.

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.

User Contributed Notes

  1. Skip to note 3 content

    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;
     }