• Sarah_Frantz

    (@sarah_frantz)


    So, I know this is possible, but I’m stuck

    I’ve got it to sum all the values of the custom fields in general, but I want it to be specific to the current user logged in. If that makes sense, here is what i have so far:

    `<?php
    $miles = array();
    $meta_key = ‘miles’;//custom field meta key
    $miles = $wpdb->get_col($wpdb->prepare(“SELECT meta_value FROM $wpdb->postmeta WHERE meta_key = %s”, $meta_key));
    echo ‘You have run’.array_sum( $miles );
    ?>

Viewing 1 replies (of 1 total)
  • Thread Starter Sarah_Frantz

    (@sarah_frantz)

    NVM solved myself.

    For those who need it, the following will find all posts by author, then sum up the values of a custom field for each post by that author.

    <?php
    			//get current user
    			global $current_user;
    		    get_currentuserinfo();
    			// build query of ids by user
    			$userPosts = get_posts(array('author' => $current_user->ID, 'post_type'=> 'miles')); //change this
    			// loop to create array of ids by user
    			foreach ($userPosts as $post) {
    			    setup_postdata($post);
    			    $ids[] = get_the_ID();
    			}
    			$idList = implode(",", $ids); //tun this crap into a list
    
    			$meta_key = 'miles';//set this to your custom field meta key
    			$allmiles = $wpdb->get_col($wpdb->prepare("
    			                                  SELECT meta_value
    			                                  FROM $wpdb->postmeta
    			                                  WHERE meta_key = %s
    			                                  AND post_id in (" . $idList . ")", $meta_key));
    			echo '<p>You\'ve completed ' . array_sum( $allmiles) . '</p>';	?>
Viewing 1 replies (of 1 total)
  • The topic ‘Sum of all custom field values posted by specific user’ is closed to new replies.