您的位置:首页 > 其它

如何调用单篇文章内的所有图片附件?

2014-05-25 18:19 267 查看
有一段时间经常碰到wordpress的图片附件问题;这里借用我在百度知道里的回答,做一节选:

wordpress如何调用单篇文章里面的所有附件图片?
http://zhidao.baidu.com/question/1987634611453390707.html?oldq=1
注意:所有图片均是通过后台上传到媒体库中的附件。


方法如下:

原理:一个文章的所有附件,是通过POSTS数据表中的post_parent挂钩的,以及post_type为attachment来标识的;

图片附件的post_mime_type为'image'。

理解这句后,查看下面这段代码:
/* 获取指定post下的所有图片附件. */
$attachments = get_children(
array(
'post_parent'      => 指定日志的ID,
'post_status'      => 'inherit',
'post_type'        => 'attachment',
'post_mime_type'   => 'image',
'order'            => 'ASC',
'orderby'          => 'menu_order ID',
'suppress_filters' => true
)
);


接下来的工作就是foreach读出附件的相关信息即可。


问题补充:

比如我的主题是有image.php这个文件。点击一篇文章中的图片即single.php模版进入image.php模版。如何实现image.php调用与之对应的跳转过来的那篇文章的附件图片。之前也有个人也是用get_children教我的。结果进入image.php调用的是之前跳转的那篇文章,所在的分类的所有文章的附件图片。也就是调用了整个分类下的附件。


解决方法:

那可能是没有正确获取当前附件所属的父级日志的ID造成的。

在image.php中,通过get_queried_object_id()获取当前附件的ID

再用wp_get_post_parent_id( $ID )来获取当前附件所属的日志ID。

最后用get_children来获取日志下的所有附件即可。

image.php中的大致代码如下:(不要放在循环内)
$current_image_id = get_queried_object_id();
$parent_id = wp_get_post_parent_id( $current_image_id );
/* 获取指定post下的所有图片附件. */
$attachments = get_children(
array(
'post_parent'      => (array)$parent_id,
'post_status'      => 'inherit',
'post_type'        => 'attachment',
'post_mime_type'   => 'image',
'order'            => 'ASC',
'orderby'          => 'menu_order ID',
'suppress_filters' => true
)
);
if ( count( $attachments ) ) {
foreach( .... ){}
}


这是无意间看到的一个方法不错,学习了!http://www.52fengjiao.com
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: