• I’m trying to add up all the comment meta for a particular meta key for a particular post. I feel like I’m close, but for some reason my output is always either ‘ArrayArrayArrayArrayArray’ or 1010101010, but I can never seem to get all those 10’s to add up. Here is what I have currently:

    <?php
    $postid = get_the_ID(); // get id of current post
    $args = array(
    	'post_id'      => $postid,
    	'count'        => false,
    	'meta_key'     => 'price',
    	'meta_value'   => '',
    	'meta_query'   => ''
    );
    
    // The Query
    $comments_query = new WP_Comment_Query;
    $comments = $comments_query->query( $args );
    
    // Comment Loop
    if ( $comments ) {
    	foreach ($comments as $comment) {
    	$rating = array($comment->meta_value);
    	echo array_sum($rating);}
    } else {
    	 echo 'no price rating to calculate';
    	}
    ?>

    >How do I get the $rating to be the added total of all the $comment->meta_value

Viewing 3 replies - 1 through 3 (of 3 total)
  • Moderator keesiemeijer

    (@keesiemeijer)

    Try it with this:

    // Comment Loop
    if ( $comments ) {
    	$rating = 0;
    	foreach ( $comments as $comment ) {
    		$rating += absint( $comment->meta_value ); // make sure it's an integer
    	}
    	echo ( $rating > 0 ) ? $rating : 'no ratings yet';
    } else {
    	echo 'no price rating to calculate';
    }

    Or with this:

    // Comment Loop
    if ( $comments ) {
    	$meta_value = wp_list_pluck( $comments, 'meta_value' ); // get all meta_values
    	$meta_value = array_map( 'intval', (array) $meta_value ); // make sure they are all integers
    	$meta_value = array_sum( $rating );
    	echo ( $rating > 0 ) ? $rating : 'no ratings yet';
    } else {
    	echo 'no price rating to calculate';
    }

    Thread Starter Sarah_Frantz

    (@sarah_frantz)

    Thanks, I actually just got it solved before I saw this – but ended up doing something a little different. This looks much cleaner than my code though haha

    Moderator keesiemeijer

    (@keesiemeijer)

    No problem. I’m glad you found your own solution ??

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘SUM items from Array?’ is closed to new replies.