WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Counting characters for all the posts (2 posts)

  1. Nessdufrat
    Member
    Posted 1 year ago #

    Hi!
    This is crazy, I know. For the sake of a funny joke on our website's name, we have decided to show the count of characters spaces included for all the published posts. Not for each post, but for the total.

    At the moment, I have this :

    <?
    global $wpdb;
    	$total_charcount = 0;
    
    	// Get all the posts
    	$result = $wpdb->get_results("SELECT post_content FROM $wpdb->posts WHERE post_status = 'publish'", OBJECT);
    
    	foreach($result as $post)
    	{
    		$total_charcount = $total_charcount + strlen(strip_tags($post->post_content));
    	}
    	echo '<p>Caractères espaces comprises :' .$total_charcount. '</p>';
    
    ?>

    But... It's showing a weird count. At the moment, the website is in construction, so I only have 4 posts published on it, mainly to test it, so it's not more than one sentence for each post, and often it's just a word.
    My characters spaces included count is at 3800. So I'm wondering... Where do all these characters come from? No way I have 3800 just by writing "testing website" in a post...
    I've tried with a plugin to get the number of words, I got 29, which is a bit more like it.
    What is wrong with my function?

    Thanks!

  2. Nessdufrat
    Member
    Posted 1 year ago #

    Hi!
    I found the solution. Actually, WordPress puts posts and pages in the same table.
    Here's the code :

    <?
    global $wpdb;
    	$total_charcount = 0;
    
    	// Get all the posts
    	$result = $wpdb->get_results("SELECT post_content FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post'", OBJECT);
    
    	foreach($result as $post)
    	{
    		$total_charcount = $total_charcount + strlen(strip_tags($post->post_content));
    	}
    	echo '<p>Characters spaces included :' .$total_charcount. '</p>';
    
    ?>

Topic Closed

This topic has been closed to new replies.

About this Topic