WordPress プラグインを使用しないでページビューランキングを表示を表示

WordPress プラグインを使用しないでページビューランキングを表示を表示
アバター
ME

記事詳細ページの閲覧回数をデータベースにカウントして、それを表示させる方法をご紹介!

1.functions.phpに以下のコードを書く

function getPostViews($postID){
    $count_key = 'post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if($count==''){
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
        return "0 View";
    }
    return $count.' Views';
}
function setPostViews($postID) {
    $count_key = 'post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if($count==''){
        $count = 0;
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
    }else{
        $count++;
        update_post_meta($postID, $count_key, $count);
    }
}
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);

2.表示させたい場所に以下のコードを書く

<?php
// クエリ発行
$args = array(
'meta_key' => 'post_views_count',
'orderby' => 'meta_value_num',
'posts_per_page' => '5',
'order' => 'DESC'
);
$postList = get_posts($args);
// ループ開始
foreach($postList as $post):
setup_postdata($post);
?>
 
<!-- サムネイルの表示 -->
<a href="<?php echo get_permalink(); ?>">
<?php if ( has_post_thumbnail() ) { the_post_thumbnail( array(40, 40) ); } ?>
</a>
 
<!-- タイトルの表示 -->
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a>
 
<?php
endforeach;
wp_reset_postdata();
?>

制作対応できるのは

202311月〜

ご相談はいつでもOK!

東京ブランド「ロゴ」