0

Using the plugin WPeddit I want to count the epicredvote score from all posts of an author together to get the sum.

The following is a custom field that puts out a score, like "3" or "-2" or whatever:

echo get_post_meta(get_the_ID(), 'epicredvote', true );

So I know, I have to build a loop somehow...

This is what I've found, but don't get a number on $allscore:

$authorPost = get_posts( array( 'author' => 1 ) );

foreach( $catPost as $post ); {
    setup_postdata( $post );
    $ids[] = get_the_ID();
}

$idList     = implode( ",", $ids );     //turn the array into a comma delimited list
$meta_key   = 'epicredvote';
$allscore   = $wpdb->get_var( $wpdb->prepare("
        SELECT sum(meta_value) 
        FROM $wpdb->postmeta 
        WHERE meta_key = %s 
        AND post_id in (" . $idList . ")
    ",
    $meta_key
) );

echo 'user 1 All posts View Count' . $allscore . ' ';
  • 1
    So what have you tried? – Mark Kaplun Nov 24 '15 at 13:56
  • Nothing actually..I just don't know how to start... – ezkay Nov 24 '15 at 17:40
  • you said it yourself, loop over the posts and do the add – Mark Kaplun Nov 24 '15 at 18:05
  • Mark, thanks, but I'm just helpless.. I know the theory, but am still learning the practice :D I edited the question with the only thing I've found that is at least a bit in the right direction? Could you have a look? – ezkay Nov 24 '15 at 18:32
  • Are you sure Author 1 has an epicredvote score? This is the first user created in the system and may / may not even exist or is likely to be an administrator. Also, you have a semi-colon at the end if your foreach statement which is not going to be valid. – Howdy_McGee Nov 24 '15 at 18:43
-1

First you have to declare the global $wpdb before using it. Also you need to include the table prefix when calling the table names.

global $wpdb;
$posts_table = $wpdb->prefix . "posts";
$posts_meta_table = $wpdb->prefix . "postmeta";

Next get an array of post ids by the author needed( make sure you have the id of desired author, assign to $author_id).

$authors_posts = $wpdb->get_col($wpdb->prepare("SELECT * FROM ".$posts_table." WHERE post_author = %d", $author_id) );

Make a comma delimited version of the post id array for SQL

$comma_delimited = implode(',', array_map('intval', $author_posts));

Next use the id array to make a sum of 'epicredvote' from the post meta table. Note the # of votes is stored in the meta_value column

$allscore = $wpdb->get_var( $wpdb->prepare(
    "SELECT SUM(meta_value) 
    FROM " .$posts_meta_table . "
    WHERE (meta_key = 'epicredvote' 
           AND post_id IN %s)"
   , $comma_delimited));
  • Thanks Emily, but I get ": implode(): Invalid arguments passed in" – ezkay Nov 25 '15 at 11:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.