Quantcast
Channel: Staff BLOG –ホームページ制作やリニューアル制作と印刷物デザインのWPC大阪
Viewing all articles
Browse latest Browse all 22

プラグインなしで関連記事をランダム抽出し、投稿の最初の画像をサムネイル表示するWordPress覚書

$
0
0

プラグインなしで関連記事を抽出して、投稿にある画像をサムネイル表示したいと思います。 アイキャッチ(サムネイル)は登録してないけど、投稿には画像あるよって時に使えるんじゃないでしょうか。
(アイキャッチがある時の場合も追記してます)

related-thumb

capture

functions.phpに記述

まず、functions.phpにて記事内の最初の画像を取得させます。

function catch_first_image() {
    global $post, $posts;
    $first_img = '';
    $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
    $first_img = $matches [1] [0];
   
    if(empty($first_img)){
        $first_img = get_template_directory_uri() .  "/images/no-image.png";	//画像がない時表示
    }
    return $first_img;
}

テンプレートファイルを作成

single.phpに直接記述しても良いのですが、
少しコードが長くなるので、テンプレートファイルを作成してインクルードさせてみます。(インクルード方法関連→記事
「related-section.php」というファイルに下記を記述して作成し、テーマにアップロードしてください。

<?php
$categories = get_the_category($post->ID);
$category_ID = array();
	foreach($categories as $category):
		array_push( $category_ID, $category -> cat_ID);
	endforeach ;
$args = array(
	'post__not_in' => array($post -> ID),		//今見ている記事は出力させない
	'posts_per_page'=> 3,						//3件表示
	'category__in' => $category_ID,				//カテゴリに属する記事
	'orderby' => 'rand',						//ランダム
);
$query = new WP_Query($args);
	if( $query -> have_posts() ):
		while ($query -> have_posts()) : $query -> the_post(); ?>

	    <div class="related-section">
	      <div class="related-section-thumb">
	  		<a href="<?php the_permalink() ?>" title="<?php the_title_attribute(); ?>">
	          <img src="<?php echo catch_first_image(); ?>" alt="<?php the_title(); ?>" width="120">
	          <!--functions.phpで取得した画像-->
			</a>
	      </div>
	      
	      <div class="related-section-content">
	        <h4 class="related-section-title">
				<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
			</h4>
	        <p class="related-section-snippet">
				<?php echo mb_substr( strip_tags( $post->post_content  ), 0, 50 ) . '...'; //記事本文の50文字抜粋 ?>
			</p>
	        <p class="related-section-read">
				<a href="<?php the_permalink(); ?>">詳細を読む</a>
			</p>
	      </div>
	    </div>
  
  		<?php endwhile;?>
  
  	<?php else:?>
  		<p>関連記事はありませんでした</p>
	<?php endif; wp_reset_postdata(); ?>

<br style="clear:both;">

9行目:表示する件数
20行目:画像幅は120pxになっています。
30行目:記事抜粋50文字になっています。
適宜変更してください。

テンプレートを読み込む

読んでいる記事の関連記事を表示したいので、記述はsingle.phpになるかと思います。
single.phpの記事内の挿入したい場所に、以下のコードでテンプレートを読み込ませます。

<div id="related-article">
  <h3>関連記事</h3>
  <?php get_template_part( 'related', 'section' ); ?>
  もしくは
  <?php include( TEMPLATEPATH . '/related-section.php' ); ?>
</div>

5行目のインクルードはWordPress3.0以前の読み込み方ですが一応書いときます。

CSS

CSSで装飾します。
こちらも適宜変更してくださいね。

#related-article h3{
  font-size:18px;
}
 
.related-section{
  clear: both;
  line-height:1.5;
  margin-bottom:20px;
  margin-top:10px;
}
 
.related-section-thumb {
  float: left;
  margin-bottom: 5px;
  padding-bottom: 5px;
}
 
.related-section-content {
  margin-left: 130px;
}
 
.related-section-title{
    margin-bottom:5px;
}
 
.related-section-snippet{
  margin-bottom:5px;
}
 
.related-section-read{
  margin:0;
  font-size:12px;
  text-align:right;
}

以上で、今見ているカテゴリに属する関連記事が、サムネイル付きで表示されたかと思います。

応用

1.最初の画像ではなく、サムネイルを使用するなら
「related-section.php」内「related-section-thumb」部分を

      <div class="related-section-thumb">
		<a href="<?php the_permalink() ?>" title="<?php the_title_attribute(); ?>">
        <?php if ( has_post_thumbnail() ): 							// サムネイルを持っているとき
        		echo get_the_post_thumbnail($post->ID, 'thumb120'); //サムネイルを呼び出す
         	  else: // サムネイルを持っていないとき ?>
        		<img src="<?php echo get_template_directory_uri(); ?>/images/no-image.png" alt="NO IMAGE" width="120" />
        <?php endif; ?>
        </a>
      </div><!-- /.related-section-thumb -->

2.最初の画像ではなく、投稿記事内の画像のいずれかを取得するなら
(検証不足ですが、いずれかというのは画像が複数ある時に最初の画像ではないのが表示されたので)
「related-section.php」内「related-section-thumb」部分を

      <div class="related-section-thumb">
  		<a href="<?php the_permalink() ?>" title="<?php the_title_attribute(); ?>">
        <?php
			$args = array(					//投稿記事の添付画像を取得
			    'post_type' => 'attachment',
			    'posts_per_page' => 1,
			    'post_status' => null,
			    'post_parent' => $post->ID
			    ); 
			$attachments = get_posts($args);
			if ($attachments) {
			    foreach ($attachments as $attachment) {
			        echo wp_get_attachment_image( $attachment->ID, 'thumb120' );	//サムネイルサイズ
			    }
			}
			?>
		</a>
      </div><!-- /.related-section-thumb -->

1.2.共に、先に書いたfunctions.php内の
function catch_first_image() { ... }
の記述は不必要なのと、
functions.php内のサムネイル関連に
add_image_size('thumb120',120,120,true);
を記述するのをお忘れなく。

多分動くと思いますが、自己検証してください^^;
参考になれば幸いです―


Viewing all articles
Browse latest Browse all 22

Trending Articles