archive.phpカテゴリリストにポストサムネイル(添付ファイル)を表示する

wordpress.stackexchange https://wordpress.stackexchange.com/questions/1542

  •  16-10-2019
  •  | 
  •  

質問

各投稿に添付された最初の画像のサムネイル画像を表示するように、カテゴリリスト(archive.php)をカスタマイズしようとしています

ただし、どうやらarchive.phpファイルは、添付ファイルをネイティブにサポートしていないファイルの1つです。たとえば、以下のコードは私が望むもののほとんどを実行します(ただし、添付ファイルが見つからない場合は、空白の画像を取得します。修正する必要があります)。

しかし、私はこのようなループにセレクトを持っていることは、おそらく私がやろうとしていることにはあまりにも高価すぎるのではないかと心配しています。

何か案は?

    <?php while (have_posts()) : the_post(); ?>
    <?php global $wpdb; $attachment_id = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_parent = '$post->ID' AND post_status = 'inherit' AND post_type='attachment' ORDER BY post_date DESC LIMIT 1"); ?>
        <div class="searchItem" style="clear:both;">
            <h3 id="post-<?php the_ID(); ?>"><img src="<?php echo wp_get_attachment_url($attachment_id); ?>" class="post-attachment" /><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h3>
            <small><?php the_time('l, F jS, Y') ?></small>
            <div class="excerpt"><?php echo $post->post_excerpt; ?></div>
            <div class="postmetadata">Posted in <?php the_category(', ') ?> | <?php comments_popup_link('No Comments &#187;', '1 Comment &#187;', '% Comments &#187;'); ?></div>
        </div>
    <?php endwhile; ?>
役に立ちましたか?

解決

WordPress関数get_childrenを使用できます。パフォーマンス面では、違いが生じるとは思いませんが。

<?php while (have_posts()) : the_post(); ?>
    <?php $attachment = array_values( get_children( array( 'post_parent' => $post->ID, 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC', 'numberposts'  => 1 ) ) ); ?>
    <div class="searchItem" style="clear:both;">
        <h3 id="post-<?php the_ID(); ?>">
        <?php if( $attachment ) echo '<img src="' . wp_get_attachment_url($attachment[0]->ID) . '" class="post-attachment" />'; ?>
        <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h3>
        <small><?php the_time('l, F jS, Y') ?></small>
        <div class="excerpt"><?php echo $post->post_excerpt; ?></div>
        <div class="postmetadata">Posted in <?php the_category(', ') ?> | <?php comments_popup_link('No Comments &#187;', '1 Comment &#187;', '% Comments &#187;'); ?></div>
    </div>
<?php endwhile; ?>

他のヒント

WPにはこれを表示するコア関数があります。私の投稿を参照してください http://wpengineer.com/1735/easier-better-solutions-to-get-pictures--- your-posts/

ライセンス: CC-BY-SA帰属
所属していません wordpress.stackexchange
scroll top