0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

WP 記事のランキング(手動)

Posted at

記事のアクセス数などをプラグインで集計取ってランキング表示、みたいなのはよくあるんですが、手動でランク付かつ管理画面から編集するというのをみかけず。

ふと日曜の昼に思いついて月曜にクライアントから即OKもらった案を備忘録で書いとく。

必要なもの

  • WP(v5.3でやりました)
  • ACF(無料でOK)

手順

  1. カスタム投稿で「ランキング」を作る。
  2. ACFで「関連>投稿オブジェクト」、単数選択を1位〜任意ランク数分フィールドを作る。「ランキング」に出るようにする。返り値は「投稿オブジェクト」
  3. 「ランキング」で記事を作る。タイトルを任意につける。
  4. 出力用のテンプレートを作る。「page-ranking.php」とか。
  5. 「page-ranking.php」の中をこんな感じに作る
page-ranking.php
/*
 Templete Name: ランキング
*/


<?php /* 関連投稿を取得 */
  $rank_args = array(
    'post_type' => 'ranking',
    'posts_per_page' => 1/*1記事だけ*/
  );
  $rank_query = new WP_Query( $rank_args ); 
  if(have_posts()):
  while($rank_query->have_posts()): $rank_query->the_post(); /*▽ ループ開始 ▽*/ 
    $rank_1 = get_field('rank_1');
    $rank_2 = get_field('rank_2');
    $rank_3 = get_field('rank_3');
?>

<h1><?php the_title(); /*タイトル出したい時*/ ?>ランキング</h1>
<p><?php the_content(); /*一言コメントとか出したい時*/ ?></p>


<?php if($rank_1): /*1位とする記事を選択していたら*/ ?>
<div>
<div class="rank">1位</div>
<h4 class="title"><?php echo $rank_1->post_title; ?></h4>
<?php if(get_the_post_thumbnail($rank_1->ID)):
  echo get_the_post_thumbnail( $rank_1->ID,'full');
  else: 
?>
<img src="<?php echo get_template_directory_uri(); ?>/assets/img/ranking/noimg.jpg" alt="" />
<?php endif; ?>
</div>
<?php endif; ?>


<?php if($rank_2): /*2位とする記事を選択していたら*/ ?>
<div>
<div class="rank">2位</div>
<h4 class="title"><?php echo $rank_1->post_title; ?></h4>
<?php if(get_the_post_thumbnail($rank_1->ID)):
  echo get_the_post_thumbnail( $rank_1->ID,'full');
  else: 
?>
<img src="<?php echo get_template_directory_uri(); ?>/assets/img/ranking/noimg.jpg" alt="" />
<?php endif; ?>
</div>
<?php endif; ?>

<?php if($rank_3): /*3位とする記事を選択していたら*/ ?>
<div>
<div class="rank">3位</div>
<h4 class="title"><?php echo $rank_1->post_title; ?></h4>
<?php if(get_the_post_thumbnail($rank_1->ID)):
  echo get_the_post_thumbnail( $rank_1->ID,'full');
  else: 
?>
<img src="<?php echo get_template_directory_uri(); ?>/assets/img/ranking/noimg.jpg" alt="" />
<?php endif; ?>
</div>
<?php endif; ?>

<?php endwhile; wp_reset_postdata(); else: /*△ ループ終了 △*/ ?>
<p>まだ投稿はありません。</p>
<?php endif; ?>

6. 固定ページを作って、テンプレートで↑のを選択

終わり。

過去のランキングを記事として残しておけるし下書きでおいてもおけるので管理しやすいと思います。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?