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() ) :
   $the_query->the_post();
   $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);
   arsort($word_frequencies);
   print_r($word_frequencies);
  endwhile;
 endif;

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)?

Was it helpful?

Solution

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 = '';
while($the_query->have_posts()){
    $the_query->the_post();
    $authorfood = get_the_author_meta('favourite_food');
    if(strlen($authorfood)>0){
    $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.

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top