飞龙博客

feilong.org 前端开发教程

wordpress theme get first attachment img function

飞龙更新于 2010-11-21 07:53 加入书签 CTRL+D 有 104 个朋友来过

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

<?php //feilong get first attach <img> 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);
}
?>
<?php echo $feilong_attach_first_img; ?>

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

<?php
//in functions.php feilong get first attachment <img>
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.

飞龙初发:
2010-11-21 07:53
本文更新网址:
https://feilong.org/wordpress-theme-get-first-attachment-img-function

所在目录: wordpress

新作:

旧文:

  • html css js
  • angular react vue
  • flutter python