【wordpress】 記事の一覧ページのカスタマイズ
◼︎記事のタイトルと概要をリストアップする
functions.phpに
//概要(抜粋)の省略記号 function my_excerpt_more($more) { return '…'; } add_filter('excerpt_more', 'my_excerpt_more');
省略記号が変更される。
category.php
<?php get_template_part('content', excerpt); ?>
に変更。
これで、content-excerpt.phpが読み込まれる。
content-excerpt.phpを作成
<div class="post"> <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> <p class="postcat"><?php the_category(' '); ?></p> <?php the_excerpt(); ?> <p class="more"><a href="<?php the_permalink(); ?>">続きを読む</a></p> <p class="postinfo"> <?php echo get_the_date(); ?> </p> </div>
「 WP Multibyte Patch」プラグインを有効にする。
◼︎概要の末尾に改行を入れずにリンクを追加する
functions.php
//概要(抜粋)の末尾に「続きを読む」リンクを追加 function my_more_link($excerpt) { return $excerpt . ' <a href="'. get_permalink($post->ID) . '" class="more">[続きを読む]</a>'; } add_filter('wp_trim_excerpt', 'my_more_link');
に変更。デザインも、
/* 続きを読む */ div.post a.more {font-size: smaller}
として文字サイズを小さく。
◼︎概要の文字数を指定する。
WP Multibyte Patchプラグインは110文字を抽出する。
この文字数の変更は、
functions.php
//概要(抜粋)の文字数 function my_excerpt_mblength($length) { return 30; } add_filter('excerpt_mblength', 'my_excerpt_mblength');
◼︎記事ごとにサムネイル画像を表示する
content-excerpt.php
<div class="post"> <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> <p class="postcat"><?php the_category(' '); ?></p> <p class="thumb"> <?php if(has_post_thumbnail()): ?> <?php the_post_thumbnail('thumbnail'); ?> <?php else: ?> <img src="<?php bloginfo('template_url'); ?>/no_image.jpg" alt="No Image" width="150" height="150" /> <?php endif; ?> </p> <?php the_excerpt(); ?> <p class="more"><a href="<?php the_permalink(); ?>">続きを読む</a></p> <p class="postinfo"> <?php echo get_the_date(); ?> </p> </div>
style.css
/* サムネイル画像 */ div.post p.thumb {float: left; margin: 0 10px 10px 0}
◼︎表示する記事の数をテンプレート内で指定する。
1ページに表示する記事の数はテンプレート内で指定することができる。
category.php
<?php query_posts('posts_per_page=-1&' . $query_string); ?> <?php if(have_posts()): while(have_posts()): ...
'posts_per_page=~$'で1ページに表示する記事の数を指定している。
$query_stringで各カテゴリーに属する記事を表示している。
また、1ページに表示する記事の数を少なくする時は、管理画面の「1ページに表示する最大投稿数」がposts_per_pageで指定する記事の数より少なくならないと404エラーになる。
◼︎古い記事から順に表示する
category.php
<?php query_posts('posts_per_page=-1&order=ASC&' . $query_string); ?>
に変更する。
order=~をつけることで記事の表示順を指定できる。
ASCはは昇順。DESCは降順。
◼︎オススメ記事を表示する
<?php query_posts('posts_per_page=2'); ?> <?php if(have_posts()): while(have_posts()): the_post(); ?> <?php get_template_part('content','excerpt'); ?> <?php endwhile; endif; ?> <ul class="toplist"> <?php query_posts('posts_per_page=8&offset=2'); ?> <?php if(have_posts()): while(have_posts()): the_post(); ?> <?php get_template_part('content','title'); ?> <?php endwhile; endif; ?> </ul>