我已经创建了一个幻灯片,可以自动填充帖子库中包含的图像,我还想显示每个图像的“标题”字段。
我当前正在使用get_post_gallery_images
循环浏览相关图像,但这只返回图像URL的数组,我需要标题数据。这个$counter
和$sizes
变量是一些额外的修饰符,用于处理Flexslider中的内容,但它们不是在图像中循环所必需的。
function get_images($post_id) {
global $post;
if( has_shortcode( $post->post_content, \'gallery\' ) ) {
$gallery = get_post_gallery_images( $post->ID ); // Returns array or URLs
$counter = -1;
$sizes = ["-300x200", "-200x300"]; // Search for medium suffixes from gallery thumbs
// Loop through each image in each gallery
foreach( $gallery as $image ) {
$counter++;
$attachment = get_post($image);
echo \'<li>\';
echo \'<img src=" \' . str_replace($sizes, \'\', $image) . \'"\';
echo \' alt="\';
echo \'" data-slide="\';
echo $counter;
echo \'" />\';
echo \'</li><!--end slide-->\';
echo \'<p class="slide-caption">\';
echo \'</p>\';
} // End for each
} // End if
} // End function
我发现使用
wp_prepare_attachment_for_js
但我认为这需要把图片附在帖子上。我想从
gallery (无论图像是否附加到此特定帖子)因为我希望客户端能够通过媒体库上传,而无需担心附件。关于如何做到这一点,我有什么想法吗?还是我只需要接受附件是必要的?
Updated code based on answer — 对于任何试图从缩略图库构建Flexslider幻灯片的人。。。这包括计算每个图像的额外变量,并为其指定data-slide
数字(Flexslider用于编程链接)。下面的答案返回缩略图或库使用的任何大小的图像,因此我想出了一种方法来解析URL并删除大小声明以返回全尺寸图像。
// GALLERY WITH CAPTIONS
function slider_from_gallery($post_id) {
if (
$gallery = get_post_gallery( get_the_ID(), false ) ) :
$img_ids = explode( \',\', $gallery[\'ids\'] );
$counter = -1;
/* Loop through all the image and output them one by one */
foreach(
$gallery[\'src\'] as $key => $src ) : ?>
<li>
<?php
$image_post = get_post( $img_ids[ $key ] );
$counter++; // Increase for each image, gets passed to data-slide below
$new_src = substr($src, 0, strrpos( $src, \'-\')) . \'.jpg\'; // Get full size by finding last occurance of - and adding .jpg
?>
<img src="<?php echo $new_src; ?>" class="slide-image" alt="Gallery image" data-slide="<?php echo $counter ?>" />
<p class="flex-caption"><?php echo $image_post->post_excerpt; ?></p>
</li>
<?php endforeach;
endif;
} //End function
最合适的回答,由SO网友:Dharmishtha Patel 整理而成
<?php $loop = new WP_Query( array( \'post_type\' => \'gallery\',
\'posts_per_page\' => 100 )
);
while ( $loop->have_posts() ) : $loop->the_post();
if ( $gallery = get_post_gallery( get_the_ID(), false ) ) :
$img_ids = explode( \',\', $gallery[\'ids\'] );
/* Loop through all the image and output them one by one */
foreach( $gallery[\'src\'] as $key => $src ) : ?>
<img src="<?php echo $src; ?>" class="my-custom-class" alt="Gallery image" />
<?php
$image_post = get_post( $img_ids[ $key ] ); ?>
<p class="wp-caption-text"><?php echo $image_post->post_excerpt; ?></p>
<?php endforeach;
endif;
endwhile; wp_reset_postdata(); ?>