WordPress|プラグインなしで関連記事や人気投稿を表示させる【記事内/ウィジェットエリア】

WordPressで有名なプラグインとして、関連記事を表示させるなら「Yet Another Related Posts Plugin(YARPP)」、人気記事を表示させるなら「wordpress popular posts」がよく知られている。
だけど関連記事や人気投稿はコードをコピペするだけで、プラグインなしで簡単に実装することができる。
もくじ
個別記事内にプラグインなしでサムネイル付き関連記事を表示させる
同カテゴリーの記事を吐き出すコード。
個別記事やウィジェットエリアなど、関連記事を表示させたい任意のテンプレート内に以下のコードをコピペ。
<!-- 関連記事 -->
<?php if( has_category() ) {
$cats = get_the_category();
$catkwds = array();
foreach($cats as $cat) {
$catkwds[] = $cat->term_id;
}
} ?>
<?php
$myposts = get_posts( array(
'post_type' => 'post',
'posts_per_page' => '6',
'post__not_in' => array( $post->ID ),
'category__in' => $catkwds,
'orderby' => 'rand'
) );
if( $myposts ): ?>
<div class="related">
<h3>関連記事</h3>
<ul>
<?php foreach($myposts as $post):
setup_postdata($post); ?>
<li><a href="<?php the_permalink(); ?>">
<div class="related-thumb">
<?php if( has_post_thumbnail() ): ?>
<?php echo get_the_post_thumbnail($post->ID, 'thumb100'); ?>
<?php else: ?>
<img src="<?php echo get_template_directory_uri(); ?>/images/no-image.png" alt="NO IMAGE" title="NO IMAGE" width="100px" />
<?php endif; ?>
</div>
<div class="related-title">
<?php the_title(); ?>
</div>
</a></li>
<?php endforeach; ?>
</ul>
</div>
<?php wp_reset_postdata();
endif; ?>
<!-- 関連記事ここまで -->
CSSでデザインを整える。
.related {margin: 40px 0;}
.related ul {list-style: none; margin: 0; padding: 0;}
.related li {margin-bottom:10px;}
.related li a {display:flex; color:#222;}
.related a img {margin: 5px 10px 10px 0; max-width:100px; max-height:80px; object-fit:cover;}
プラグインなしで人気投稿を表示させる
functions.phpに以下のコードを追記
//アクセス数をカウントする
function set_post_views() {
$postID = get_the_ID();
$num = (int)date_i18n('H'); // 現在時間で番号取得
$key = 'pv_count';
$count_key = '_pv_count';
$count_array = get_post_meta( $postID, $count_key, true );
$sum_count = get_post_meta( $postID, $key, true );
if( !is_array($count_array) ) { //配列ではない
$count_array = array();
$count_array[$num] = 1;
} else { //配列である
if ( isset( $count_array[$num] ) ) { //カウント配列[n]が存在する
$count_array[$num] += 1;
} else { //カウント配列[n]が存在しない
$count_array[$num] = 1;
}
}
//アクセス数を更新する
update_post_meta( $postID, $count_key, $count_array );
update_post_meta( $postID, $key, $sum_count + 1 );
}
//アクセス数をリセットする
function reset_post_views() {
$num = (int)date_i18n('H');
$key = 'pv_count';
$reset_key = '_pv_count';
$args = array(
'posts_per_page' => -1,
'post_type' => 'post',
'post_status'=>'publish',
'meta_key' => $reset_key,
);
$reset_posts = get_posts($args);
if($reset_posts):
foreach($reset_posts as $reset_post):
$postID = $reset_post->ID;
$count_array = get_post_meta( $postID , $reset_key, true );
if ( isset( $count_array[$num] ) ) { //カウント配列[n]が存在する
$count_array[$num] = 0;
}
//アクセス数をリセットする
update_post_meta( $postID, $reset_key, $count_array );
update_post_meta( $postID, $key, array_sum( $count_array ) );
endforeach;
endif;
}
//リセット関数を実行するアクションフックを追加
add_action( 'set_hours_event', 'reset_post_views' );
//実行間隔の追加
function my_interval( $schedules ) {
// 1時間ごとを追加
$schedules['1hours'] = array(
'interval' => 3600,
'display' => 'every 1 hours'
);
return $schedules;
}
add_filter( 'cron_schedules', 'my_interval' );
//アクションフックを定期的に実行するスケジュールイベントの追加
function my_activation() {
if ( ! wp_next_scheduled( 'set_hours_event' ) ) {
wp_schedule_event( 1451574000, '1hours', 'set_hours_event' );
}
}
add_action('wp', 'my_activation');
//ボットの判別
function isBot() {
$bot_list = array (
'Googlebot',
'Yahoo! Slurp',
'Mediapartners-Google',
'msnbot',
'bingbot',
'MJ12bot',
'Ezooms',
'pirst; MSIE 8.0;',
'Google Web Preview',
'ia_archiver',
'Sogou web spider',
'Googlebot-Mobile',
'AhrefsBot',
'YandexBot',
'Purebot',
'Baiduspider',
'UnwindFetchor',
'TweetmemeBot',
'MetaURI',
'PaperLiBot',
'Showyoubot',
'JS-Kit',
'PostRank',
'Crowsnest',
'PycURL',
'bitlybot',
'Hatena',
'facebookexternalhit',
'NINJA bot',
'YahooCacheSystem',
'NHN Corp.',
'Steeler',
'DoCoMo',
);
$is_bot = false;
foreach ($bot_list as $bot) {
if (stripos($_SERVER['HTTP_USER_AGENT'], $bot) !== false) {
$is_bot = true;
break;
}
}
return $is_bot;
}
こちらで紹介されているコードでは「1時間ごとに集計したアクセス数」で表示される。それを例えば「15日間ごとに集計したアクセス数」に変更するには、コード内「//実行間隔の追加」を以下のように書き換えればOK。
【変更前】
//実行間隔の追加
function my_interval( $schedules ) {
// 1時間ごとを追加
$schedules['1hours'] = array(
'interval' => 3600,
'display' => 'every 1 hours'
);
return $schedules;
}
add_filter( 'cron_schedules', 'my_interval' );
【変更後】
//実行間隔の追加
function my_interval( $schedules ) {
// 15日ごとを追加
$schedules['Once15days'] = array(
'interval' => 1296000, // 60s * 60m * 24h * 15d
'display' => 'Once15days'
);
return $schedules;
}
add_filter( 'cron_schedules', 'my_interval' );
人気記事を表示させる任意の場所に以下のコードを追記
<!-- 人気記事 --> <div class="ninki"> <h3>人気記事</h3> <?php if( is_single() && !is_user_logged_in() && !isBot() ): //個別投稿の場合人気記事を表示する 管理者とボットのアクセスを除外 set_post_views(); endif; ?> <?php $args = array( 'post_type' => 'post', 'numberposts' => 5, //表示数 'meta_key' => 'pv_count', 'orderby' => 'meta_value_num', 'order' => 'DESC', ); $posts = get_posts( $args ); if( $posts ): ?> <ul> <?php foreach( $posts as $post ) : setup_postdata( $post ); ?> <li><a href="<?php the_permalink(); ?>" > <div class="ninki-thumb"> <?php if( has_post_thumbnail() ): ?> <?php echo get_the_post_thumbnail($post->ID, 'thumb100'); ?> <?php else: ?> <img src="<?php echo get_template_directory_uri(); ?>/images/no-image.png" alt="NO IMAGE" title="NO IMAGE" width="100px" /> <?php endif; ?> </div> <div class="ninki-title"> <?php the_title(); ?> </div> </a></li> <?php endforeach; wp_reset_postdata(); ?> </ul> <?php else : ?> <p>アクセスランキングはまだ集計されていません。</p> <?php endif; ?> </div> <!-- 人気記事ここまで -->
CSSでデザインを整える
.ninki ul {list-style: none; margin: 0;}
.ninki-list {display: flex; border:none;}
.ninki-list img {width:100px; height:100px; margin-bottom:10px;}
.ninki-list p {padding-left:10px;}
これで簡単に人気記事を表示させることができる。
サイドバーやフッターのウィジェットエリアに関連記事・人気投稿を表示させることもできる
サイドバーやフッターのウィジェットエリアに人気記事を表示させるには、ウィジェットではなくサイドバーやフッター等のテンプレート内に直接コードを記述する必要がある。
ウィジェットの「テキスト」としてコードを記述しても機能しない。



