Looking at this, I see that “Paid”, a string, isn’t in quotes. That would cause an error. You can add $wpdb->show_errors()
and $wpdb->print_error()
methods to reveal that, and any other mysql issues.
Also when querying the database, you should use the $wpdb->prepare()
method to escape and prepare your variables for query (yes $user->ID
probably can’t be compromised, but it looks like future values in that query might be replaced, or if that value was ever changed in the future to be from $_REQUEST
— it’s just always good to escape).
I also used $wpdb->get_var()
instead of $wpdb->get_results()
as it gives you the single value you’re after which cleans things up a bit. And using $wpdb->prefix
instead of wp_
makes the plugin more compatible with other installs should this plugin/theme be released.
add_filter('gform_field_value_user_retainer', 'gform_populate_user_retainer');
function gform_populate_user_retainer($value){
global $wpdb;
$user = wp_get_current_user();
// turn on errors
$wpdb->show_errors();
// make the query
$result = $wpdb->get_var( $wpdb->prepare(
"
SELECT SUM(`payment_amount`) as `dviews`
FROM `{$wpdb->prefix}gf_entry`
WHERE `created_by` = %d
AND `form_id` = 37
AND `payment_status` = 'Paid'
",
$user->ID
) );
// if there was a query error
if ( $wpdb->last_error !== '' ) {
return "🔥 Error: " . $wpdb->print_error();
}
return $result;
}
If that doesn’t fully solve your issue:
-
If you returned
"hello world"
or123
ingform_populate_user_retainer()
, does the value appear where you expect? If it doesn’t, isgform_field_value_user_retainer
the correct hook? -
If you
echo "<pre>".$wpdb->prepare("..."); die();
the string query instead of running it, and pasted it into MySQL, does it work? If it doesn’t follow the MySQL error to resolve. -
If you
echo "<pre>"; print_r($result);die();
the$result
instead of returning it, do you see what you expect to return? If not, revise the query. -
If you
echo "<pre>"; print_r($user);die();
do you see what you expect? For yourself and other users? none-users?