development_creative

この記事は1年以上経過しています。

【WordPress】プラグインなし!wordpressサイトで記事のランキング機能を実装する

プラグインでどんどん重くなる一方のWordpress・・・
開発している側としては、余計な記述は一切排除したいものである。

また、記述を把握していれば、改善はもちろんのこと
トラブル時の原因の特定・解決も早い・・・。

今回は記事の閲覧数をカウントし、ランキング順で表示するコードを掲載します!

まずはコードをどうぞ

// 人気記事出力用関数
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';
}
// 記事viewカウント用関数
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);

こいつをfunctions.phpに貼り付けて・・・

このコードを該当のファイルに。
大体はsingle.phpに使用することが多いかな?

<div class="popular-article-list">
   <?php if ($query->have_posts()) : while ($query->have_posts()) : $query->the_post(); ?>
      <div class="ranking-contents">
         <?php the_category();?>
         <span class="rank"><?php echo $count++; ?></span>
         <a class="thumnail" href="<?php echo get_permalink(); ?>">
             <?php if ( has_post_thumbnail() ) { the_post_thumbnail( 'post-thumbnail'); } ?>
         </a>
         <a class="title" href="<?php the_permalink(); ?>">
            <?php echo mb_substr($post->post_title, 0, 30).'…'; ?>
         </a>
         <?php echo getPostViews(get_the_ID()); // 記事閲覧回数表示 ?>
      </div>
    <?php endwhile; ?>
    <?php endif; ?>
  <?php wp_reset_postdata(); ?>
</div>

class名とかは適当です。
こいつにうまいことcssを記述すると、こんな感じのランキングになります。

これからも俺のwordpressマスターへの道は終わらない・・

結構友達になれたと思っていたら、
まだそこまで仲良くないんだな〜と、痛感するwordpress。
まだまだ、俺たちには奥行きがある。

とにかく日々触り続けて、仲良くなっていくしかないね。
俺は諦めないからな!毎日ヨシヨシするんだからな!

今後とも、僕の奮闘を応援してくれよな!!!

Related ariticle

関連記事

TOP