在wordpress中使用wp_get_attachment_image()的正确方法

Con*_*ing 5 php wordpress wordpress-theming

我正在寻找使用wp_get_attachment_image()的正确方法.

以下代码:

<?php
    $args = array(
        'type' => 'attachment',
        'category_name' => 'portfolio'
        );
    $attachments = get_posts($args);
    print_r($attachments);
?>
Run Code Online (Sandbox Code Playgroud)

生成以下结果:

Array
(
    [0] => stdClass Object
        (
            [ID] => 54
            [post_author] => 1
            [post_date] => 2010-06-22 00:32:46
            [post_date_gmt] => 2010-06-22 00:32:46
            [post_content] => <a href="http://localhost/wordpress/wp-content/uploads/2010/06/Capture.jpg"><img class="alignnone size-medium wp-image-55" title="Capture" src="http://localhost/wordpress/wp-content/uploads/2010/06/Capture-300x114.jpg" alt="" width="300" height="114" /></a> 
            [post_title] => Our Own Site
            [post_excerpt] => 
            [post_status] => publish
            [comment_status] => open
            [ping_status] => open
            [post_password] => 
            [post_name] => our-own-site
            [to_ping] => 
            [pinged] => 
            [post_modified] => 2010-06-22 00:40:22
            [post_modified_gmt] => 2010-06-22 00:40:22
            [post_content_filtered] => 
            [post_parent] => 0
            [guid] => http://localhost/wordpress/?p=54
            [menu_order] => 0
            [post_type] => post
            [post_mime_type] => 
            [comment_count] => 0
            [filter] => raw
        )
)
Run Code Online (Sandbox Code Playgroud)

但是,以下内容不会返回任何内容.

<?php
    echo wp_get_attachment_image(54, array('300', '300'));
?>
Run Code Online (Sandbox Code Playgroud)

我在这做错了什么?

rin*_*ogo 8

实际上,我认为接受的答案并不能真正回答这个问题.

你的问题是你传递的帖子ID(54在你的例子中;通常$post->ID用WP的说法)来wp_get_attachment_image().由于可以在可见抄本,你应该使用固定的ID(见$attachment_id下文):

wp_get_attachment_image( $attachment_id, $size, $icon );
Run Code Online (Sandbox Code Playgroud)

换句话说,你必须做这样的事情:

$image_attr = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'medium');
Run Code Online (Sandbox Code Playgroud)


Aar*_*run 3

该函数wp_get_attachment_image仅获取上传到 WordPress 的图像,不会输出帖子内容中的图像。

您必须输出示例图像的帖子内容。

喜欢:echo $attachments['post_content'];