skip to Main Content

WordPress Code Snippets


How to Count Rows in a WordPress Database Efficiently

This snippet demonstrates how to count the number of rows in a table using $wpdb->get_var(). By using this method, you can quickly retrieve the row count. First, establish a connection to your WordPress database. Then, run the query to get the number of rows from your table. Finally, the result will be returned as a single value, giving you the total count.

global $wpdb;

$count = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}posts WHERE post_status = 'publish'");
echo "There are $count published posts.";


I’m a WordPress developer with 10+ years of experience in WooCommerce and custom plugins. I combine technical expertise with design flair to help you create standout, user-friendly websites. Let’s transform your digital presence!

Best WordPress Hosting
Back To Top
Search