WordPressでサムネイル入り新着記事一覧を作る

DSC_8820

WordPressで運用しているクライアントさんのサイトのトップページに、画像サムネイル入りの新着記事一覧を作りました。

ネット上に意外と情報が少なくて手を焼いたので、メモしておきます。


こんな感じのコードを書きました。

[php]
<?php
query_posts(‘&posts_per_page=5’);
if (have_posts()):
while(have_posts()): the_post();
?>

<h2><a href="<?php the_permalink(); ?>" ><?php the_title(); ?></a></h2>
<div class="list_day">[<?php echo get_the_date(‘Y年n月j日’); ?>]</div>

<?php
if (has_post_thumbnail()) {
the_post_thumbnail( array(180,9999) );
} else {
$postImage = getPostImage($post);
if($postImage){
echo ‘<img alt="’ . $postImage["alt"] . ‘" src="’ . $postImage["url"] . ‘" width="180" style="float:right;margin:20px 0 10px 20px" />’;
}
}
$content = get_the_content();
$content = preg_replace("/<a.+?><img.+?></a>/","",$content);
$content = trim($content);
$content = apply_filters(‘the_content’, $content);
$content = str_replace(‘]]>’, ‘]]&gt;’, $content);
?>

<div class="top_list_contents"><?php echo $content; ?></div>

<?php endwhile; endif; ?>
[/php]

今回はサムネイル画像とコンテンツの冒頭部(more以前)を、リスト表示しました。

コンテンツから画像タグを消去するために、the_content()ではなく、get_the_content()を利用しました。get_the_content()は生データを取り扱えます。データの取回し方がポイントです。

[php]
$content = preg_replace("/<a.+?><img.+?></a>/","",$content);
$content = trim($content);
[/php]

最初にimgタグを取っ払い、trim()でコンテンツ前後のスペースや改行を削除してしまうことがコツです。そして最後に、

[php]
$content = apply_filters(‘the_content’, $content);
$content = str_replace(‘]]>’, ‘]]&gt;’, $content);
[/php]

で整形します。両方ともthe_content()で使われているフィルターで、pタグや改行タグ等を入れてくれます。get_the_content()を使う上で常套手段です。

ご参考にどうぞ。

【追記】
getPostImage()とthe_post_thumbnail()を利用するには、function.phpファイルに記述が必要です。ネタ元が分からないので、掲載しておきます。

[php]
<?php
function getPostImage($mypost){
if(empty($mypost)){ return(null); }
if(ereg(‘<img([ ]+)([^>]*)src=["|’]([^"|^’]+)["|’]([^>]*)>’,$mypost->post_content,$img_array)){
$dummy=ereg(‘<img([ ]+)([^>]*)alt=["|’]([^"|^’]+)["|’]([^>]*)>’,$mypost->post_content,$alt_array);
$resultArray["url"] = $img_array[3];
$resultArray["alt"] = $alt_array[3];
}
else{
$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);
}

add_theme_support( ‘post-thumbnails’ );
?>
[/php]

今日のわかった

MovabletypeからWordPressへ移行したとき、やりにくさを感じたのですが、慣れてしまえばPHPでいくらでもカスタマイズができるので、これはこれで便利ですね。

WordPress
スポンサーリンク
当ブログの記事に共感していただけたら、また読みに来ていただけると嬉しいです。読んでくれる方の数が多くなると、更新するヤル気に繋がります(^^)
フォロー、ブックマークしていただけると、ブログ更新を見逃しません
わかったブログ

コメント

タイトルとURLをコピーしました