飞龙博客

妙法莲华经

wordpress theme get first attachment img function

feilong.org 修订于2010-11-21 07:53:36 215 次浏览

How to get first attachment img in a wordpress theme files eg index.php?Here feilong give you one resolution.

 used in a loop 20101121 shenzhen
$args = array(
'order'          => 'ASC',
'post_type'      => 'attachment',
'post_parent'    => $post->ID,//feilong for current post in a loop
'post_mime_type' => 'image',
'post_status'    => null,
'numberposts'    => 1,
);$attachments = get_posts($args);if ($attachments) {
$feilong_attach_first_img = wp_get_attachment_image($attachments[0]->ID, 'thumbnail', false);
}
?>

Of course,you can put it in functions.php too.Then use this function somewhere in your theme.


function feilong_get_attach_first_img($postid,$size='thumbnail') {
$args = array(
'order'          => 'ASC',
'post_type'      => 'attachment',
'post_parent'    => $postid,
'post_mime_type' => 'image',
'post_status'    => null,
'numberposts'    => 1,
);$attachments = get_posts($args);if ($attachments) {
$feilong_attach_first = wp_get_attachment_image($attachments[0]->ID, $size, false);
return $feilong_attach_first;}
}
//then somewhere in your loop of wordpress theme  
echo $feilong_get_attach_first_img($post->ID);
?>

There are other ways to display wordpress attachment.Perhaps wp_get_attachment_image_src() is a more free wordpress function for you to code and resolve attachment problems.For more,contact me.

更新网址:https://feilong.org/wordpress-theme-get-first-attachment-img-function
最初发布:20101121 07:53:36 feilong.org 于广州

加入收藏夹,查看更方便。

所在分类: wordpress

新作:

旧文: