WordPressで記事を人気ランキング順に表示する方法

今回はプラグインを使わずに記事を人気ランキング順に表示する方法です。

function.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);
PHP

ランキングを表示させたいPHPファイル

<?phpsetPostViews( get_the_ID() ); //記事のアクセス数を取得する関数$args = new WP_Query( array( 'post_type' => 'post', //投稿タイプ 'posts_per_page' => 5, //表示数 'meta_key' => 'post_views_count', //カスタムフィールド名 'orderby' => 'meta_value_num', //カスタムフィールドの値 'order' => 'DESC' //降順で表示する ));if ( $args->have_posts() ):?><ul> <?php while ( $args->have_posts() ) : $args->the_post(); ?> <li><a href="<?php the_permalink(); ?>"> <?php the_title(); ?> <?php echo get_the_post_thumbnail(); ?> <!-- 記事のアクセス数を表示する関数 --> <?php echo getPostViews( get_the_ID() ); ?> </a></li> <?php endwhile; ?></ul><?php endif; wp_reset_postdata();?>
PHP

read next