Add Snippet To Project
If you are managing a WordPress website, it is essential to keep track of the number of posts, pages, comments, and custom post types available on your website. This information can help you understand the structure of your website and the content published on it. In this article, we’ll show you how to count the number of posts, pages, comments, and custom post types in WordPress using different methods. Whether you prefer using plugins or some code snippets, we’ve got you covered. So, let’s get started!
function wpturbo_count_all_content() {
$args = array(
'public' => true,
'_builtin' => false
);
$post_types = get_post_types( $args, 'names', 'and' );
array_push( $post_types, 'post', 'page' );
$total_posts = 0;
foreach ( $post_types as $post_type ) {
$count_posts = wp_count_posts( $post_type );
$total_posts += $count_posts->publish;
}
$total_comments = wp_count_comments()->approved;
$total_content = $total_posts + $total_comments;
echo '<p>' . sprintf( esc_html__( 'There are %s published posts and pages and %s approved comments.', 'wpturbo' ), $total_posts, $total_comments ) . '</p>';
}
add_action( 'admin_notices', 'wpturbo_count_all_content' );
This code snippet provides a convenient way to count all the content on a WordPress site including posts, pages, comments, and custom post types.
The first part of the function wpturbo_count_all_content
sets up the $args
array with two parameters: 'public' => true
and '_builtin' => false
. This means the function only includes custom post types and excludes built-in post types like post
and page
.
Next, we get the list of post types using the get_post_types()
function. We also include 'post'
and 'page'
in the post types array. This gives us a list of all the post types we need to count.
Then we set $total_posts
to zero, and iterate over $post_types
array using foreach
loop. Inside the loop, we use wp_count_posts()
function with the current post type to get the count of published posts. We add the count to the $total_posts
variable.
Following that, we use wp_count_comments()
function to get a count of all approved comments and assign it to $total_comments
.
Finally, we use the sprintf()
function to display the total number of published posts and pages and approved comments by passing the $total_posts
and $total_comments
variable values to the string that we want to display using a translation-friendly method, and then we echo the output.
Lastly, we hook the wpturbo_count_all_content
function to the admin_notices
action using add_action()
to display the result of calculated content in the WordPress admin dashboard.