John Davidson

Summing Values From Meta Fields in PHP (Wordpress)

0 comments
Message:


I am trying to update a custom field by 'adding' a number from a front-end form to the existing number in the field.
The script I wrote is not adding the existing number, but just updating to the number entered in the form.


I think there needs to be some sort of conversion for what the get_post_meta function is returning, so the script understands it as a number.


The script is:


if(isset($_POST['Add_Work_Task'])){

$Work_Required_Hours=$_POST['Work_Required_Hours'];
$Parent_Work=$_POST['Work_Parent_TaskGroup'];
$Current_Buried_Hours =get_post_meta( $Parent_Work, 'Work_Buried_Hours',true);

$Total_Buried_Hours= $Current_Buried_Hours + $Work_Required_Hours;

$Buried_Required_Hours= array('Work_Buried_Hours' => $Total_Buried_Hours);
wp_update_post(array(
'ID' => $Parent_Work,
'meta_input'=> $Buried_Required_Hours,
));

}

I also tried


$Total_Buried_Hours= (float)$Current_Buried_Hours + (float)$Work_Required_Hours;

$Total_Buried_Hours= floatval($Current_Buried_Hours) + floatval($Work_Required_Hours);

$Total_Buried_Hours= $Current_Buried_Hours += $Work_Required_Hours;

$Total_Buried_Hours= print_r($Current_Buried_Hours) + $Work_Required_Hours; this one adds 1 only.

and


$Current_Buried_Hours =implode(".",get_post_meta( $Parent_Work, 'Work_Buried_Hours',true));

To narrow it down I know for a fact the problem is with the get_post_meta function, I have tested adding the $_POST twice and it worked like the following:


$Total_Buried_Hours= $Work_Required_Hours + $Work_Required_Hours;


My Answer:
$Total_Buried_Hours);

update_post_meta($Parent_Work, 'Work_Buried_Hours', $Total_Buried_Hours);
}

In this script, you need to convert the values returned by get_post_meta to integers before performing addition. You can do this by using the intval() function. Here's the updated script:

if(isset($_POST['Add_Work_Task'])){
$Work_Required_Hours = intval($_POST['Work_Required_Hours']);
$Parent_Work = $_POST['Work_Parent_TaskGroup'];
$Current_Buried_Hours = intval(get_post_meta($Parent_Work, 'Work_Buried_Hours', true));
$Total_Buried_Hours = $Current_Buried_Hours + $Work_Required_Hours;
$Buried_Required_Hours = array('Work_Buried_Hours' => $Total_Buried_Hours);

update_post_meta($Parent_Work, 'Work_Buried_Hours', $Total_Buried_Hours);
}

By using intval() to convert the values to integers, you can perform addition correctly and update the custom field with the sum of the existing value and the value entered in the form.

Rate this post

4 of 5 based on 7228 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us