2690

WordPressで前後の記事に含まれる画像を表示する方法

WordPressで前後の記事に含まれる画像を表示する方法

2011.9.24

WordPressで前後の記事に含まれる画像を表示する方法をメモ。

WordPressで「次の記事」「前の記事」のリンクを表示しようとコードを探すと、以下のようなコードをよく見かけます。

これで問題はないのですが、どうせならテキストだけではなく、その記事に含まれる画像のサムネイルも表示したい。と思ったので調べてみました。

確認環境

functions.phpに「記事に含まれる1枚目の画像を抽出する」コードを追加

以前「自分用メモ:WordPressスニペット2|1bit::memo」で紹介した、記事の1枚目の画像を抽出するコードをfunctions.phpに記述します。


]*)src=["|']([^"|^']+)["|']([^>]*)>',$mypost->post_content,$img_array)){
  // imgタグで直接画像にアクセスしているものがある
    $dummy=ereg(']*)alt=["|']([^"|^']+)["|']([^>]*)>',$mypost->post_content,$alt_array);
    $resultArray["url"] = $img_array[3];
    $resultArray["alt"] = $alt_array[3];
  }else{
  // 直接imgタグにてアクセスされていない場合は紐づけられた画像を取得
    $files = get_children(array('post_parent' => $mypost->ID, 'post_type' => 'attachment', 'post_mime_type' => 'image'));
    if(is_array($files) && count($files) != 0){
      $files=array_reverse($files);
      $file=array_shift($files);
      $resultArray["url"] = wp_get_attachment_url($file->ID);
      $resultArray["alt"] = $file->post_title;
    }else{
      return(null);
    }
  }
  return($resultArray);
}
?>

get_adjacent_post()関数で前後の記事を取得する

以下をsingle.phpに記述してください。


    
    

" alt="post_title); ?>" height="200" width="200" />

<?php echo esc_attr($prevpost->post_title); ?>

<?php $nextpost = get_adjacent_post(true, '', false); if ( $nextpost ) : ?>
<?php $postImage2 = getPostImage($nextpost);if($postImage2 != null){ //記事内に画像があったら ?>

" alt="post_title); ?>" height="200" width="200" />

<?php echo esc_attr($nextpost->post_title); ?>

参考