Search code examples
wordpressfieldadditionword-count

WordPress: Add Word Count as field for all posts


have in functions.php I have created a small function that counts words within a post:

function prefix_wcount(){
    global $post;
    ob_start();
    the_content();
    $content = ob_get_clean();
    return sizeof(explode(" ", $content));
    $word_count = prefix_wcount();
}

Now I would like to add a field to all posts that contains this number. For that I added

add_post_meta($post_id, $meta_key, $meta_value, $unique);

This does not add this field however. What do I need to do to make this happen?

Thanks a lot


Solution

  • You could create a meta box first and simply display it. Technically you wouldn't need an editable field.

    With this you may need to adjust your initial word count function.

    // Create a meta box to display the word count
    
    function wordcount_meta_box() {
        add_meta_box( 'box-1', __( 'Post Word Count', 'wcf' ), 'show_word_count', 'post' );
    }
    add_action( 'add_meta_boxes', 'wordcount_meta_box' );
    
    
    // Create callback function to display data in meta box
    
    function show_word_count( $post ) {
        $word_count = prefix_wcount( $post ); // Get the word count
        echo $word_count; // Display the count
    }