How to Add a Real-Time Word Count Overlay to WordPress Gutenberg Blocks?

Have you ever wondered how many words you’ve written in each paragraph while crafting your WordPress posts? Learn how to add a smart, real-time word count overlay that appears as you write in the Gutenberg editor. This handy tool even warns you when paragraphs get too long!

What Does This Feature Do?

This clever addition to your WordPress editor:

  • Shows a live word count for each paragraph and heading
  • Displays a floating counter that follows your cursor
  • Changes color when paragraphs exceed 300 words
  • Works seamlessly within the Gutenberg interface
  • It helps you maintain optimal paragraph lengths for better readability

(see the screenshot below)

Why You Need This Feature?

  1. Improved Readability: Keep your paragraphs concise and reader-friendly
  2. Better Content Structure: Instantly identify overly long paragraphs
  3. SEO Benefits: Maintain optimal content structure for search engines
  4. Writing Efficiency: Monitor word count in real-time without switching tools

Installation Options

Method 1: Using WPCode Plugin (Recommended for Beginners)

  1. Install the free WPCode plugin from WordPress.org
  2. Navigate to Code Snippets → Add Snippet
  3. Create a new snippet
  4. Select “PHP Snippets” as the code type
  5. Copy and paste our provided code
  6. Set “Location” to “Universal”
  7. Activate the snippet
  8. Save your changes
// Add a Real-Time Word Count Overlay to WordPress Gutenberg Blocks
function enqueue_word_count_overlay() {
    // Only load on Gutenberg editor pages
    if (!is_admin()) return;

    // Add styles for the word count overlay
    wp_add_inline_style('wp-edit-blocks', '
        .word-count-overlay {
            position: absolute;
            background: #f0f0f0;
            color: #666;
            padding: 2px 6px;
            border-radius: 3px;
            font-size: 11px;
            pointer-events: none;
            z-index: 9999;
            white-space: nowrap;
        }
        .word-count-overlay.long {
            background: #fff3cd;
            color: #856404;
        }
    ');

    // Add JavaScript for word count functionality
    wp_add_inline_script('wp-blocks', '
        wp.domReady(function() {
            // Create a reusable overlay element for word counts
            const overlay = document.createElement("div");
            overlay.className = "word-count-overlay";
            document.body.appendChild(overlay);

            const updateOverlay = (block, rect, wordCount) => {
                if (!block || !rect) return;

                overlay.textContent = `${wordCount} words`;
                overlay.style.left = `${rect.left + rect.width - 80}px`;
                overlay.style.top = `${rect.top - 20}px`;
                overlay.style.display = "block";

                if (wordCount > 300) {
                    overlay.classList.add("long");
                } else {
                    overlay.classList.remove("long");
                }
            };

            const hideOverlay = () => {
                overlay.style.display = "none";
            };

            // Update the overlay dynamically
            const updateWordCount = () => {
                const blocks = wp.data.select("core/block-editor").getBlocks();

                const activeBlock = wp.data.select("core/block-editor").getBlockSelectionStart();
                const blockData = blocks.find(block => block.clientId === activeBlock);

                if (blockData && ["core/paragraph", "core/heading"].includes(blockData.name)) {
                    const blockElement = document.querySelector(`[data-block="${blockData.clientId}"]`);
                    const rect = blockElement?.getBoundingClientRect();

                    const content = blockData.attributes.content || "";
                    const wordCount = content.trim().split(/\s+/).filter(word => word.length > 0).length;

                    updateOverlay(blockElement, rect, wordCount);
                } else {
                    hideOverlay();
                }
            };

            // Monitor block selection and content changes
            wp.data.subscribe(updateWordCount);

            // Hide overlay on editor clicks
            document.querySelector(".edit-post-layout").addEventListener("click", hideOverlay);
        });
    ');
}
add_action('enqueue_block_editor_assets', 'enqueue_word_count_overlay');

Method 2: Child Theme Method (Advanced Users)

While possible, we don’t recommend adding this to your child theme’s functions.php because:

  • You might lose the functionality during theme updates
  • It’s harder to manage and maintain
  • There’s a higher risk of syntax errors

How to Use the Word Count Overlay?

Once installed, the feature works automatically:

  1. Open any post or page in the Gutenberg editor
  2. Click on any paragraph or heading block
  3. Look for the word count overlay in the top-right corner of the block
  4. Watch it update as you type
  5. Notice the yellow warning when exceeding 300 words

Customization Options

Want to adjust the feature? Here are some common modifications:

Change the word limit warning:

  • Find: wordCount > 300
  • Adjust the number to your preferred limit

Modify the overlay colors:

  • Normal state: Edit the #f0f0f0 value
  • Warning state: Edit the #fff3cd value

Adjust the position:

  • Modify the left and top values in the JavaScript

Troubleshooting Common Issues

If the word count overlay isn’t appearing:

  1. Clear your browser cache
  2. Ensure WordPress is updated
  3. Check if your theme supports Gutenberg
  4. Verify the code is properly activated
  5. Disable conflicting plugins temporarily

Pro Tips for Writers

  • Use this tool to maintain consistent paragraph lengths
  • Aim for 2-3 sentences per paragraph for web content
  • Break up paragraphs showing the yellow warning
  • Consider your audience when setting word count limits

Conclusion

Adding a word count overlay to your Gutenberg editor is a simple yet powerful way to improve your content creation process. While there are several ways to implement this feature, the WPCode plugin method offers the best combination of ease and reliability for most users.

Do you want to thank me and buy me a beer?

Every donation is entirely welcome but NEVER required. Enjoy my work for free but if you would like to thank me and buy me a beer or two then you can use this form here below.

Donation Form (#2)

Here are some of my favorite WordPress tools

Thanks for reading this article! I hope it's been useful as you work on your own websites and e-commerce sites. I wanted to share some tools I use as a WordPress developer, and I think you'll find them helpful too.

Just so you know, these are affiliate links. If you decide to use any of them, I'll earn a commission. This helps me create tutorials and YouTube videos. But honestly, I genuinely use and recommend these tools to my friends and family as well. Your support keeps me creating content that benefits everyone.

Themes: Over the past few years, I've consistently relied on two primary themes for all sorts of projects: the Blocksy theme and the Kadence Theme. If you explore this website and my YouTube channel, you'll come across numerous tutorials that delve into these themes. If you're interested in obtaining a 10% discount for both of these themes, then:

Code Snippets Manager: WPCodeBox allows you to add code snippets to your site. Not only that, but it also provides you with the capability to construct and oversee your WordPress Code Snippets library right in the cloud. You can grab it with the 20% discount here (SAVE 20% Coupon: WPSH20).

Contact forms: There are hundreds of contact forms out there but Fluent Forms is the one I like the most. If you need a 20% discount then use this link (save 20% coupon is WPSH20).

Gutenberg add-ons: If I need a good Gutenberg blocks add-on then Kadence Blocks is the one I have used the most. You’ll get a 10% discount with the coupon SIMPLEHACKS here.

Website migration: While building a website you probably need a good plugin that can help you with the migration, backups, restoration, and staging sites. Well, WpVivid is the one I have used for the last couple of years. If you use this link along with the WPSH20 coupon you’ll get a 20% discount.

Woocommerce extensions: There are a bunch of Woocommerce extensions that I like but the one that stands out is Advanced Dynamic Pricing. Once again, you’ll get a 20% discount if you use this link here (save 20% coupon is WPSH20)

Web Hosting: If you would like to have a really fast and easy-to-use managed cloud hosting, then I recommend Verpex Hosting (see my review here). By the way, this site is hosted in Verpex.)

To see all my most up-to-date recommendations, check out this resource that I made for you!

Janek T.
Janek T.

Improve this text: {CLIPBOARD}

- I have been passionate about Wordpress since 2011, creating websites and sharing valuable tips on using Wordpress and Woocommerce on my site.
- Be the first to receive notifications about new tutorials by subscribing to my Youtube channel .
- Follow me on Twitter here

Articles: 134