web-dev-qa-db-ja.com

Single.phpの先頭に添付ファイルを表示する

最新のWPを使用しています。投稿の先頭に、投稿に添付されている最初の画像を表示します。これを実現するためにどのようなコードをsingle.phpに追加する必要がありますか?

1
Scott B

添付ファイルは、添付されている投稿の子と見なされるので、これでうまくいくはずです。

$images=get_children( array('post_parent'=>$post->ID,
                            'post_mime_type'=>'image',
                             'numberposts'=>1));
echo wp_get_attachment_image($images[0]->ID, 'large');

大きな画像の場合は、 "large"を必要なサイズ定義または幅、高さの配列に置き換えます。

2
goldenapples

投稿に最初の画像を添付する機能

function the_image($size = 'medium' , $class = ”){
global $post;

//setup the attachment array
$att_array = array(
'post_parent' => $post->ID,
'post_type' => 'attachment',
'post_mime_type' => 'image',
'order_by' => 'menu_order'
);

//get the post attachments
$attachments = get_children($att_array);

//make sure there are attachments
if (is_array($attachments)){
//loop through them
foreach($attachments as $att){
//find the one we want based on its characteristics
if ( $att->menu_order == 0){
$image_src_array = wp_get_attachment_image_src($att->ID, $size);

//get url – 1 and 2 are the x and y dimensions
$url = $image_src_array[0];
$caption = $att->post_excerpt;
$image_html = '<img src="%s" alt="%s" />';

//combine the data
$html = sprintf($image_html,$url,$caption,$class);

//echo the result
echo $html;
}
}
}
}

今度はWordPressにこの画像を表示する場所を指示する必要があります

画像を表示したい場所にこの行を追加します。

<?php the_image('medium','post-image'); ?>

このアプローチを使うためのガッチャ

投稿エディタに画像を追加すると、2回表示されます。

この方法を使用する場合

ブログページでサムネイル(注目の画像)を使用してから、より大きなバージョンの画像をsingle.phpで表示し、注目の画像を設定して手動で挿入する必要がない場合は、これは非常に便利です。この方法では、投稿に添付してそれを実行するように注目の画像を設定するだけです。

1
Chris_O

最初の添付ファイルに限定する方法(および画像の添付ファイルに限定する方法)はわかりませんが、これは良い出発点になるはずです。 From The Codex

<?php

$args = array(
    'post_type' => 'attachment',
    'numberposts' => -1,
    'post_status' => null,
    'post_parent' => $post->ID
    ); 
$attachments = get_posts($args);
if ($attachments) {
    foreach ($attachments as $attachment) {
        echo apply_filters('the_title', $attachment->post_title);
        the_attachment_link($attachment->ID, false);
    }
}

?>
0