What I'm trying to do is query and sum a custom field in Wordpress for the current logged in user.
I have a website for my writing company that lets writers log in and claim work that they want to do. For each assignment, there is a field called "Word Count" where I input the word count for the article that needs to be done. To calculate how much each writer is owed for an assignment, I use the word count field (with the meta key "assignment_word_count" ) and multiply it by a flat rate that each writer is paid per word.
So far the closest script I've put together that does what I want it do is an SQL script. Unfortunately, it sums ALL of the word count fields instead of just the ones that belong to the current user. If I try to add anything to the code to limit it to the current user, the total drops to zero.
<?php
$now = current_time('mysql');
$sql = "SELECT ";
$sql .= "meta_value FROM $wpdb->posts AS posts, $wpdb->postmeta AS postmeta ";
$sql .= "WHERE posts.ID = postmeta.post_id AND postmeta.meta_key = 'assignment_word_count' ";
$sql .= "AND posts.post_status = 'paid' ";
$sql .= "AND posts.post_date < '$now' ";
$sql .= "AND postmeta.meta_value != '' ";
$results = array(); $values = array();
$results = $wpdb->get_results($sql);
$totalpay = 0;
if (!empty($results)){
foreach ($results as $result) {
$totalpay += $result->meta_value;
}
}
echo 'Total Paid: $' . $totalpay * money_format('0.0040=(#10.2n', $number);
?>
There's also another script I found that is supposed to do exactly what I'm looking for, but it tells me that the implode line is an invalid argument.
<?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'=> 'assignments')); //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 = 'assignment_word_count';//set this to your custom field meta key
$totalpay = $wpdb->get_col($wpdb->prepare("
SELECT meta_value
FROM $wpdb->postmeta
WHERE meta_key = %s
AND post_id in (" . $idList . ")", $meta_key));
echo 'Total pay: $ ' . array_sum( $totalpay); ?>