For the 'view all' screens which list posts (edit-post) and pages (edit-page) how can I add an extra admin column with the word count of individual posts/pages?

Having previously used the 'admin columns' plugin, and aware of alternatives, I'm wondering if there's a simpler filter/function?


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

  • Thanks. If I understand correctly, your suggestion of 'calc words only once on save_post hook' differs from the on-the-fly code. I don't know enough to do this, so if you've more info I'll be grateful. (And if you don't have more info, that's of course ok - thanks again for helping.) – glvr Aug 24 '17 at 8:03
  • I've updated the post. Feed free to ask questions – Anton Lukin Aug 24 '17 at 9:30
  • thanks, again. With increasing brain-fade (at this rate I'll probably soon struggle to read/write/understand my own name), I'm not smart enough to understand how to use the revised code ('YOUR_WORD_COUNT_VALUE' has me immediately perplexed). – glvr Aug 24 '17 at 15:27
  • I've made the gist with final solution for you gist.github.com/antonlukin/dd22530f180300e67385025568521081 – Anton Lukin Aug 24 '17 at 15:54
  • Thanks. Hugely appreciated. I re-saved all posts to add the count. – glvr Aug 25 '17 at 15:18

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.