WordPress - 2017-12-16

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
setPostViews( 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();?>
Related Posts

Related Posts

WordPress Popular Postsのサムネイルをaタグの中に入れる方法-出力内容カスタマイズ

2020-06-17

WordPressのカスタムフィールドやカテゴリを検索対象に含める方法

2018-02-07

WordPressでCSSやJSファイルのキャッシュ対策

2022-06-24

WordPressのDB情報をSTG環境と本番環境で分ける方法

2022-07-07