Counting instances of words in the results of a post query

The question:

I’m way over my head with this one and wonder if anyone can shine a light on where I’m going wrong.

I am grabbing some authormeta for the resulting posts of a query, and I want to tally up the number of times certain authormeta is repeated in those results.

E.g. There are 10 ‘recipe’ posts > The author of each post (different for each one) has a ‘favourite food’ meta item > I want the result to be something like “3 recipe authors have ‘pie’ as their favourite food”.

Here’s what I’ve done so far, which has gotten me close, but I’d need the results of $authorfood to be used in $text but it seems it only works with a plain text statement?

$the_query = new WP_Query( array( 'post_type' => 'recipe', 'posts_per_page' => -1 ) );
 if ( $the_query->have_posts() ) :
  while ( $the_query->have_posts() ) :
   $authorfood = get_the_author_meta( 'favourite_food' ); // the result of this is the plain list I want to use later, e.g. "appleappleappleapplebananapiepiepie"
   $text = "Plain text to count frequency of words"; // this needs to be the result of $authorfood above
   $words = str_word_count($text, 1);
   $word_frequencies = array_count_values($words);

I’m probably going about this completely the wrong way. Sorry for the stupid question, but I’ve searched and searched and can’t find an answer.

Any ideas how I can tally the number of ‘favourite foods’ of ‘recipe authors’ (it has to be specifically those post authors, rather than all authors on the site, as there are multiple post types)?

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

What I understand from your question is that you want to:

Count how many times the words inside a certain user meta field are repeated accross all the meta results for a query.

One way to achieve this is to put all your meta values together into one string and then count the repeated words in that new string.

// Create a string with all favorite foods
$all_favorites = '';
    $authorfood = get_the_author_meta('favourite_food');
    $all_favorites .= ' '.$authorfood;

// Count
$words = explode(' ', $all_favorites);
$counts = array();
foreach($words as $word){
    $word = preg_replace("#[^a-zA-Z-]#", "", $word);
    $counts[$word] += 1;

Then, the $counts variable will be an array with the structure (key) "food" => (value) count for all the words that appear in your site’s favourite_food user meta values.

Note: This will become heavy once you reach a high number of users. A better approach would be to save the user’s favorite food (or foods) as independent entities with unique ids where you can then easily count things.

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment