View Word Count Per Post in Your WordPress Admin Posts List
I recently had a project where I wanted to quickly find all posts at a glance that had very low word count (e.g. >100 words). There weren't many good off-the-shelf options. I also was hoping I could come up with a solution that didn't require another plugin. Thankfully I did just that!
Here's the code; you can simply pop this into your functions.php file and you'll see a new "Word Count" column in your WordPress posts list:
// Add Word Count column to posts list
function add_word_count_column($columns) {
$columns['word_count'] = 'Words';
return $columns;
}
add_filter('manage_posts_columns', 'add_word_count_column');
function populate_word_count_column($column, $post_id) {
if ($column === 'word_count') {
$content = get_post_field('post_content', $post_id);
$word_count = str_word_count(strip_tags($content));
echo number_format($word_count);
}
}
add_action('manage_posts_custom_column', 'populate_word_count_column', 10, 2);
function make_word_count_column_sortable($columns) {
$columns['word_count'] = 'word_count';
return $columns;
}
add_filter('manage_edit-post_sortable_columns', 'make_word_count_column_sortable');
function add_word_count_column_style() {
echo '<style>
.column-word_count { width:100px;text-align:right!important; }
.wp-list-table tbody .column-word_count { padding-right:20px!important;color:#666; }
</style>';
}
add_action('admin_head', 'add_word_count_column_style');
function handle_word_count_sorting($query) {
if (is_admin() && $query->get('orderby') === 'word_count') {
$query->set('meta_key', '_word_count');
$query->set('orderby', 'meta_value_num');
}
}
add_action('pre_get_posts', 'handle_word_count_sorting');
function update_word_count_on_save($post_id) {
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
if (wp_is_post_revision($post_id)) return;
if (get_post_type($post_id) !== 'post') return;
$count = str_word_count(strip_tags(get_post_field('post_content', $post_id)));
update_post_meta($post_id, '_word_count', $count);
}
add_action('save_post', 'update_word_count_on_save');
Did this help you? Please let me know in the comments below! Your feedback keeps me going and encourages me to keep sharing custom code snippets like these 🙂
Comments