programing

워드프레스에서 wp_get_attachment_image()를 올바르게 사용하는 방법

stoneblock 2023. 3. 15. 17:49

워드프레스에서 wp_get_attachment_image()를 올바르게 사용하는 방법

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이 예에서는 일반적으로$post->IDWP용어로)에 대해서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');

wp_get_management_image 함수는 다음과 같이 4개의 값을 받아들일 수 있습니다.

wp_get_attachment_image ( int $attachment_id, string|array $size = 'thumbnail', bool $icon = false, string|array $attr = '' )

그래서 항상 사용하고 있습니다.

<?php echo wp_get_attachment_image( get_the_ID(), array('700', '600'), "", array( "class" => "img-responsive" ) );  ?>

주의: get_the_를 간단하게 사용할 수 있습니다.ID()는 활성 투고의 ID를 전달합니다.여기서 700은 폭, 600은 첨부 이미지의 높이입니다.또한 클래스를 어레이("class" => "img-response")로 전달할 수도 있습니다.

함수wp_get_attachment_image워드프레스에 업로드된 이미지만 가져오고 게시물의 내용에 이미지는 출력되지 않습니다.

샘플 이미지에 대한 투고 내용을 출력해야 합니다.

예를 들어 다음과 같습니다.echo $attachments['post_content'];

언급URL : https://stackoverflow.com/questions/3089624/correct-way-of-using-wp-get-attachment-image-in-wordpress