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

标签 php wordpress wordpress-theming

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

以下代码:

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

生成以下结果:

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
        )
)

然而,以下内容不返回任何内容。

<?php
    echo wp_get_attachment_image(54, array('300', '300'));
?>

我在这里做错了什么?

最佳答案

实际上,我认为接受的答案并没有真正回答问题。

您的问题是您要传递帖子 ID(在您的示例中为 54;在 WP 中通常为 $post->ID说法)到 wp_get_attachment_image()。在codex中可以看出,您应该使用附件 ID(请参阅下面的 $attachment_id):

wp_get_attachment_image( $attachment_id, $size, $icon );

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

$image_attr = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'medium');

关于php - 在 wordpress 中使用 wp_get_attachment_image() 的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3089624/

相关文章:

php - MySql PHP 从逗号分隔的数据(标签)中选择不同值的计数

wordpress - 在 Wordpress 上嵌入私有(private) Tableau 仪表板

php - add_theme_support 不适用于 functions.php

wordpress - 如何在 Wordpress 3 中将自定义字段添加到我的自定义帖子类型?

css - 自定义 CSS 文本对齐不起作用

php - mysql_insert_id();成功插入行后未返回值

php - 元素未从 DOM 中删除

PHP解析错误帮助(working with MySQL)

php - 在 WooCommerce 中检查购物车中的多个产品 ID

html - CSS 菜单在 IE 中左对齐,但在 Chrome 中居中对齐