Skip to content
Read For Learn
Read For Learn
  • Database
    • Oracle
    • SQL
  • C
  • C++
  • Java
  • Java Script
  • jQuery
  • PHP
Read For Learn
  • Database
    • Oracle
    • SQL
  • C
  • C++
  • Java
  • Java Script
  • jQuery
  • PHP

Display post number by category

Add this code to functions.php. It should add meta value to posts from given category.
You can use hardcoded category slug/ID, but maybe it would be better to store it in options table and allow to change from dashboard.

Change “ID”https://wordpress.stackexchange.com/”category_slug” to your own.

/**
 * @param int     $post_ID      Post ID.
 * @param WP_Post $post_after   Post object following the update.
 * @param WP_Post $post_before  Post object before the update.
 */
function updateNumbers($post_id, $post_after, $post_before) {
    global $wpdb;

    if ( $post_after->post_type != 'post' )
        return;

    $selected_cat_ID = 123; // <-- ID of your category with numbering

    // -- select category ID by slug --
    // $selected_cat="category_slug";
    // $selected_cat_ID = get_terms(['slug' => 'category_slug', 'fields'=> 'ids', 'taxonomy' => 'category', 'hide_empty' => false,]);
    // if ( !is_array($selected_cat_ID) || empty($selected_cat_ID) ) 
    //     return; 
    // $selected_cat_ID = $selected_cat_ID[0];
    // -- end: select category ID by slug --

    $incr_number = get_post_meta($post_id, 'incr_number', true);

    //
    // get posts assigned to your category
    $query = "SELECT p.id FROM {$wpdb->posts} p"
                . " LEFT JOIN {$wpdb->term_relationships} tr ON tr.object_id = p.id"
                . " LEFT JOIN {$wpdb->term_taxonomy} tt ON tt.term_taxonomy_id = tr.term_taxonomy_id"
                . " LEFT JOIN {$wpdb->terms} t ON t.term_id = tt.term_id"
            . " WHERE p.post_status="publish" AND p.post_type="post""
            // if you want use slug instead ID change "AND t.term_id = %d" to "AND t.slug = %s"
            . " AND tt.taxonomy = 'category' AND t.term_id = %d"  
            . " ORDER BY p.post_date ASC";
    $ids = $wpdb->get_results( $wpdb->prepare($query, $selected_cat_ID), OBJECT );

    // is post assigned to category after update
    $in_category = false;
    $assigned_posts = [];

    foreach( $ids as $row ) {
        $assigned_posts[] = $row->id;
        if ( $row->id == $post_id )
            $in_category = true;
    }

    if ( !$in_category && $incr_number === '' ) {
        //
        // after the update post is not in the category, before the update was not either
        return;
    }
    else if ($in_category && $incr_number !== '' && $post_before->post_date_gmt == $post_after->post_date_gmt ) {
        //
        // after the update, post is still in the category,
        // publish date has not changed,
        // numbering doesn't need to be changed
        return;
    }
    else if ( !$in_category && $incr_number !== '' ) {
        //
        // post has he been removed from category
        delete_post_meta($post_id, 'incr_number');
    }

    // update numbering
    if ( !empty($assigned_posts) ) {
        $counts = 0;
        foreach( $assigned_posts as $pid )
            update_post_meta($pid, 'incr_number', ++$counts);
    }
}
add_action( 'post_updated', 'updateNumbers', 10, 3);

Related Posts:

  1. How to add category to: ‘wp-admin/post-new.php’?
  2. Sanitizing `wp_editor();` Values for Database, Edit, and Display
  3. Exporting Data from WordPress into a flat table
  4. Extracting post categories
  5. if in category but only with post meta
  6. Saving Post Data in Another Database
  7. Get post category as a separate string and url
  8. Post meta not working
  9. Is there a way to save different data when USER interacts with the same POST?
  10. More Than 50K Categories and WordPress Admin Panel Stop Showing Categories and Posts
  11. Re-order Category Meta-data
  12. How to make category for word post_content
  13. What effect can a large wp_post table have on overall site performance?
  14. Site ‘Categories’: save an admin global setting with post metadata [closed]
  15. How to get a list of all posts and their categories?
  16. Emojis replaced by ‘?’ automatically
  17. Prepending %category% onto default posts fails
  18. List all categories with featured image from post?
  19. How to compare two posts including their meta fields on a scalable base?
  20. Categories list into registration form
  21. WordPress Local And Live Site
  22. Getting value from get_post_custom
  23. WP_Query: Mixing category__in and tag__in together
  24. If in_category not working for multiple single.php pages
  25. Calling Different Custom Post Timestamps in a table
  26. How can I setup a relationship using categories in WordPress?
  27. WordPress Multisite – Create Default Post and New Category On New Site Install
  28. how to show single post in a custom template
  29. Can’t update old posts 3.5.2
  30. Using ajax on editing a category edit page?
  31. Is it possible to paste a link without tags and make it directly a link in a post?
  32. Related posts by category not working right
  33. How to list recent posts in a wp nav menu?
  34. Set Default Category to Username
  35. Disable sticky option for specific categories
  36. Dynamic dependent Dropdown lists for categories, sub-categories and posts
  37. How can I hide tags on a child-category page, if that tag has not been used?
  38. date issue with category post retrival
  39. Cannot retrieve a custom RSS field from posts
  40. Copy post to separate database with “add_action(….)”
  41. Listing Specific Categories from Current Post with Depth
  42. How to make multiple sections in home pulling posts category wise?
  43. How to display two blog categories as separate sections on one page?
  44. When open add new post or page WordPress add post with ID=0 continuously [closed]
  45. Saving custom fields to a custom taxonomy
  46. wp_posts table: safely remove unused columns to save database storage
  47. How to make the first post in the loop be styled like a “new / featured” post?
  48. Anyone know why wordpress converts some html entities to their numeric equivalents?
  49. How to Mysql select a list of posts with meta_values AND all relevant categories?
  50. Remove a shortcode from all WordPress posts
  51. Display post category in foreach loop
  52. Single.php – Get Current Parent Category
  53. How do I stop the loop from repeating in my category template?
  54. get_the_category listing in hierarchial order
  55. How to automate featured posts number? [duplicate]
  56. What do these phpMyAdmin errors mean on my WordPress databaes?
  57. Is it possible to add/tick a category to a post when it is created?
  58. Excluding posts not working
  59. Hide posts belongs to few categories in homepage
  60. What happens if I delete all the rows that represents a post revision from the posts table into WordPress database?
  61. why does wordpress ignore the post args?
  62. post category in wp_insert_post
  63. Limit the number of posts a category can have – newest post goes in, oldest one drops out, possible? plugin?
  64. why there are so many posts whoes post_type is revision? will these records waste too much database space?
  65. How to get subcategories from category slug?
  66. Remove current category from post but display all others
  67. How show categories in admin and get that selected to show posts in index
  68. Delete all drafts?
  69. Customize rel=canonical tag for single blog post
  70. Change all author links in Blog roll
  71. How to I retrieve the ID from the Posts page?
  72. How to save meta checkbox WordPress
  73. Is it possible to use WP_Query to only pull posts with attachments?
  74. Showing categories and subcategories with posts
  75. Change default category when I publish a post
  76. store posts_id of category into a varable?
  77. Get posts and include taxonomy term
  78. Why my wp_posts data is so huge?
  79. How to display two random-post sections that are each under their own category
  80. How can you display all sibling categories to a post?
  81. How to calculate the average of a post meta value(Numeric) of a specific author
  82. Loop doesn’t exclude the specified category in home page
  83. Is there any way to tell when wp_postmeta has been updated?
  84. Display posts of specific category term
  85. Add field to user meta table in database when link is clicked
  86. Widget that shows categories with posts numbers
  87. How to create a sub post?
  88. Post Image not displaying in category view
  89. How do I show posts from another wordpress installation?
  90. How safe is it to delete old posts edits to save database space?
  91. wpColorPicker – problem with implementation to post meta
  92. get posts from Custom Post Type & Category
  93. Category page when using static front page
  94. Latest posts by category — how to exclude current post?
  95. How do I include the category next to the title of a post?
  96. Relative number of post in category
  97. How to create a “latest news” page showing a list of posts from blog category
  98. WordPress bulk category select when publishing post
  99. Exclude some categories from listing on the current post
  100. How to show a custom taxonomy in the theme?
Categories posts Tags categories, database, post-meta, posts
CSS getting injected into index from somewhere after theme/custom CSS is loaded, overriding all of my CSS [closed]
PHP -> SQL Query with Summing

Recommended Hostings

Cloudways: Realize Your Website's Potential With Flexible & Affordable Hosting. 24/7/365 Support, Managed Security, Automated Backups, and 24/7 Real-time Monitoring.

FastComet: Fast SSD Hosting, Free Migration, Hack-Free Security, 24/7 Super Fast Support, 45 Day Money Back Guarantee.

Recent Added Topics

  • Bug in translation system: load_theme_textdomain() returns true, files are available and accessible but the language defaults to english
  • Custom Elementor controls not appearing in the widget Advanced tab using injection hooks
  • Get the name of the template/*html file used
  • Trying to Add Paging to Single Post Page
  • Sharing media files between live and staging servers
  • How to display the description of a custom post type in the dashboard?
  • Critical error on image display
  • Copying WP data and files into new install?
  • How to determine the DirectAdmin WordPress backup date?
  • How to get list of ALL tables in the database?
© 2026 Read For Learn
  • Database
    • Oracle
    • SQL
  • algorithm
  • asp.net
  • assembly
  • binary
  • c#
  • Git
  • hex
  • HTML
  • iOS
  • language angnostic
  • math
  • matlab
  • Tips & Trick
  • Tools
  • windows
  • C
  • C++
  • Java
  • javascript
  • Python
  • R
  • Java Script
  • jQuery
  • PHP
  • WordPress