How can I add an extra admin column showing the word-count of a page or post?

It is not really difficult. Manage columns in posts list you can with 2 hooks: manage_posts_columns, manage_posts_custom_column

add_filter('manage_posts_columns', 'wordcount_column');
function wordcount_column($columns) {
    $columns['wordcount'] = 'Word count';
    return $columns;
}

add_action('manage_posts_custom_column',  'show_wordcount');
function show_wordcount($name) 
{
    global $post;
    switch ($name) 
    {
        case 'wordcount':
            $wordcount = YOUR_WORD_COUNT_VALUE
            echo $wordcount;
    }
}

Then you only need calc word count after save_post to post_meta and show counts in columns.

add_action('save_post', function($post_id, $post, $update) {
    $word_count = str_word_count( strip_tags( strip_shortcodes($post->post_content) ) );

    update_post_meta($post_id, '_wordcount', $word_count);
}, 10, 3);

Related gist

Another way is to calc words count on-the-fly.

function post_word_count($post_id) {
    $content = get_post_field( 'post_content', $post_id );
    $word_count = str_word_count( strip_tags( strip_shortcodes($content) ) );
    return $word_count;
}

Related gist

But I suggest to calc words only once on save_post hook. Note that better save it in post_meta starting with underscore

For example: _wordcount

Leave a Comment