最近做主題時要用到wordpress 附件圖片,在看數據庫時發現,原來每一個附件都是作為一個post插入數據庫,只是post-type不同,而且還有是屬於哪個post。在文章中也可以直接插入gallery。
看到這些功能,心動了,只是這些自帶的功能缺乏的東西就是附件圖片的描述。
根據說明,取得附件的function 是wp_get_attachment_image($id,size),這樣加一個foreach就能取得到post裡面的所有附件圖片,不過就是缺少介紹。
用google找到了一篇不錯的文件,寫了一個hack,可以取得附件圖片的title, description
[php]
/**
* Retrieves the attachment data such as Title, Caption, Alt Text, Description
* @param int $post_id the ID of the Post, Page, or Custom Post Type
* @param String $size The desired image size, e.g. thumbnail, medium, large, full, or a custom size
* @return stdClass If there is only one result, this method returns a generic
* stdClass object representing each of the image’s properties, and an array if otherwise.
*/
function getImageAttachmentData( $post_id, $size = ‘thumbnail’, $count = 1 )
{
$objMeta = array();
$meta;// (stdClass)
$args = array(
‘numberposts’ =$count,
‘post_parent’ =$post_id,
‘post_type’ = ‘attachment’,
‘nopaging’ =false,
‘post_mime_type’ =’image’,
‘order’ = ‘ASC’, // change this to reverse the order
‘orderby’ = ‘menu_order ID’, // select which type of sorting
‘post_status’ = ‘any’
);
$attachments = get_children($args);
if( $attachments )
{
foreach( $attachments as $attachment )
{
$meta = new stdClass();
$meta-ID = $attachment-ID;
$meta-title = $attachment-post_title;
$meta-caption = $attachment-post_excerpt;
$meta-description = $attachment-post_content;
$meta-alt = get_post_meta($attachment-ID, ‘_wp_attachment_image_alt’, true);
// Image properties
$props = wp_get_attachment_image_src( $attachment-ID, $size, false );
$meta-properties[‘url’] = $props[0];
$meta-properties[‘width’] = $props[1];
$meta-properties[‘height’] = $props[2];
$objMeta[] = $meta;
}
return ( count( $attachments ) == 1 ) ? $meta : $objMeta;
}
}
[/php]
如何使用:
[php]
getImageAttachmentData( $_posts-ID, ‘full’ );
[/php]
參考來源:http://www.farfromfearless.com/
http://www.newvibes.com/blog/wordpress-get-attachment-title-and-description/