1

I'm trying to figure out how can I display the amount of posts ever posted - not only the currently published, draft + pending etc ones, but even the deleted ones.

I assume that there has to be created some kind of a counter that every time a post is published gets increased by one.

Any ideas?

P.S. I'm talking about a custom post type

1

Depending on your needs, WP Query may not work for this since it won't include posts that have been deleted after the trash has been emptied. This should work (but hasn't been tested):

function wpse_custom_post_type_counter() {
     $number = get_option( 'wpse_custom_counter' ) ? absint( get_option( 'wpse_custom_counter' )  ): 0;
     $number++;
     update_option( 'wpse_custom_counter', $number );
}
add_action( 'publish_your_custom_post_type', 'wpse_custom_post_type_counter' );

You'll need to update the function and option names to suit your application. Also the slug for your custom post type should replace your_custom_post_type in the call to add_action.

One disadvantage of this approach is that it will only work going forward, it won't be able to count existing posts.

Hope that helps!

3
  • I upvoted this as it is probably good enough for many real life sites, but it actually not as simple as you count the same post twice if it is being unpublished and then published again. Aug 31 '15 at 3:50
  • Looks to be exactly what I need and thank you for answering. So I added this to functions.php, went to header.php and added <?php code echo $number?> but nothing is echoed.. Most probably it's elementary stuff that I'm doing wrong but I'd appreciate your reply in any case!
    – Jim
    Aug 31 '15 at 18:23
  • figured it out - rookie mistake of course. echo get_option is what I had to do and works perfectly! Thank you very much. Solved.
    – Jim
    Aug 31 '15 at 18:46
0

Presuming you don't empty the trash on deleted posts, you can do it with a simple wp_query.

<?php
$args = array (
    'post_type'       => array( 'your-custom-post-type' ),
    'post_status'     => array( 'publish', 'trash' ),
    'posts_per_page'  => -1
);
$query = new WP_Query( $args );
$total = count($query->posts);
?>
<h1>My total: <?php echo $total; ?></h1>

You may need to augment the query based on the statuses you care about: https://codex.wordpress.org/Post_Status

1
  • IIRC Trash is being emptied automatically once a month, and even if not you just can't know if a trashed post was actually published before that. Aug 31 '15 at 3:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.