wordpress
WordPressで人気記事一覧表示-非プラグイン-期間指定Ver
作成日: 2025年1月22日
以前作った「よく見られている記事」用のテンプレだが、期間を直近30日間として、動きのあるものに変えた。
実装しているサイトでは、固まってしまうものが多く、ちょっと動きが欲しいからで、30日は数字の書き換えで変更も可能とした。
あまり使う機会はないが、ポータルサイトなどで「閲覧履歴」が表示されない1stビューの代替えなどに使える。
先ず一覧取得出力部分
<?php
$args = array(
'post_type' => 'post',
'cat' => '69,70,71,72,73,74,75,76', // カテゴリID
'meta_key' => 'post_views_recent_30_days', // 直近30日PVのメタキー
'orderby' => 'meta_value_num', // 数値として並べ替え
'posts_per_page' => 3,
'order' => 'DESC', // 降順
);
$the_view_query = new WP_Query($args);
?>
<?php if ($the_view_query->have_posts()):?>
<section class="relatedEntriesWrap">
<h2>
POPULAR POSTS
<span>人気の記事</span>
</h2>
<div class="relatedEntries cnt<?php $the_query = new WP_Query( $args );$post_count = $the_query->post_count;echo $post_count;?>">
<?php while($the_view_query->have_posts()): $the_view_query->the_post();?>
<a href="<?php the_permalink(); ?>">
<picture><?php /*通常こちらでregisterのページを人気記事に含める場合はOGPurlを拾う下のコードで
<img src="<?php the_post_thumbnail_url('thumbnail');?>" alt="<?php echo get_the_title(); ?>">*/?>
<img src="<?php $ctm = get_post_meta($post->ID, 'scraped_ogp_image_url', true);?><?php if(empty($ctm)):?><?php the_post_thumbnail_url('thumbnail');?><?php else:?><?php the_field('scraped_ogp_image_url'); ?><?php endif;?>" alt="<?php echo get_the_title(); ?>">
</picture>
<h3>
<?php echo get_the_title(); ?>
</h3>
</a>
<?php endwhile; ?>
</div>
</section>
<?php else:?>
<?php endif; ?>
<?php wp_reset_postdata(); ?>
次にfunction.php追記コード
//Popularlist 用
function update_post_views($postID) {
if (!is_single() || empty($postID)) return;
// 現在の日付(YYYY-MM-DD形式)
$today = date('Y-m-d');
// 現在のPVデータを取得
$daily_views = get_post_meta($postID, 'post_views_daily', true);
// データがない場合は初期化
if (empty($daily_views) || !is_array($daily_views)) {
$daily_views = array();
}
// 今日のPVを加算
if (isset($daily_views[$today])) {
$daily_views[$today]++;
} else {
$daily_views[$today] = 1;
}
// 直近30日間に絞る
$recent_views = array();
foreach ($daily_views as $date => $count) {
if (strtotime($date) >= strtotime('-30 days')) {
$recent_views[$date] = $count;
}
}
// 更新したデータを保存
update_post_meta($postID, 'post_views_daily', $recent_views);
// 直近30日の合計を保存
$recent_total = array_sum($recent_views);
update_post_meta($postID, 'post_views_recent_30_days', $recent_total);
}
function track_post_views($postID) {
if (!is_single() || empty($postID)) return;
update_post_views($postID);
}
add_action('wp_head', function() {
if (is_single()) {
global $post;
if (isset($post->ID)) {
track_post_views($post->ID);
}
}
});
function記述内の「-30」が直近30日なので、この数字を変えれば一年以内などになる。
これについて昨年とか指定期間などは設ける必要ないだろうからそのまま。