wordpress使用wp_get_attachment_image()获取图片标题

时间:2011-11-19 20:12:08

标签: php wordpress function

我正在尝试将图片标题添加到图库中图片的alt属性,但我的代码不起作用。以下是为实现幻灯片而修改的图库短代码的一部分。在底部,我使用wp_get_attachment_image()$default_attr作为包含标题的属性数组。标题不会以HTML格式显示。

$id = intval($id);
    if ( 'RAND' == $order )
        $orderby = 'none';

    if ( !empty($include) ) {
        $include = preg_replace( '/[^0-9,]+/', '', $include );
        $_attachments = get_posts( array('include' => $include, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );

        $attachments = array();
        foreach ( $_attachments as $key => $val ) {
            $attachments[$val->ID] = $_attachments[$key];
        }
    } elseif ( !empty($exclude) ) {
        $exclude = preg_replace( '/[^0-9,]+/', '', $exclude );
        $attachments = get_children( array('post_parent' => $id, 'exclude' => $exclude, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
    } else {
        $attachments = get_children( array('post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
    }

    if ( empty($attachments) )
        return '';

    if ( is_feed() ) {
        $output = "\n";
        foreach ( $attachments as $att_id => $attachment )
            $output .= wp_get_attachment_link($att_id, $size, true) . "\n";
        return $output;
    }
   $i = 0;


   $default_attr = array(
    'src'   => $src,
    'class' => "attachment-$size",
    'alt' => trim(strip_tags( $attachment->post_excerpt ))
    );

foreach ( $attachments as $attachment ) {
    <a href='".wp_get_attachment_url($attachment->ID)."'>".wp_get_attachment_image($attachment->ID, $size, false, $default_attr)."</a>      
}     

return $output;

2 个答案:

答案 0 :(得分:0)

您可以使用:

wp_get_attachment_url($attachment->post_title);

答案 1 :(得分:0)

在搜索相同的答案时找到了答案,找到了并希望分享它:

$attachment=get_post($attachment_id);
$alt = get_post_meta($attachment->ID, '_wp_attachment_image_alt', true);
$image_title = $attachment->post_title;
$caption = $attachment->post_excerpt;
$description = $image->post_content;

输出由wordpress格式化的标题(添加中断和段落),您可以使用:

$caption = apply_filters('the_content', $caption);