LoginSignup
2
3

More than 5 years have passed since last update.

カテゴリー中で何番目の記事か

Posted at

JOIN が多くなるのでカテゴリーの slug よりも ID を使った方が良いかもしれませんが・・・。

functions.php
function post_number_in_cat($cat_slug) {
  global $wpdb, $post;
  $number = $wpdb->get_var("
    SELECT COUNT(posts.ID)
    FROM $wpdb->posts posts
    INNER JOIN $wpdb->term_relationships rels ON posts.ID = rels.object_id
    INNER JOIN $wpdb->term_taxonomy tax ON rels.term_taxonomy_id = tax.term_taxonomy_id
    INNER JOIN $wpdb->terms terms ON tax.term_id = terms.term_ID
    WHERE terms.slug = '{$cat_slug}'
    AND posts.post_date <= '{$post->post_date}'
    AND posts.post_status = 'publish'
    AND posts.post_type = 'post'
  ;");
  return $number;
}
2
3
4

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
2
3