Skip Navigation

[Resuelto] automatically update child calculated values when parent values change using PHP

This support ticket is created hace 7 años, 1 mes. There's a good chance that you are reading advice that it now obsolete.

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

Hoy no hay técnicos de soporte disponibles en el foro Juego de herramientas. Siéntase libre de enviar sus tiques y les daremos trámite tan pronto como estemos disponibles en línea. Gracias por su comprensión.

Sun Mon Tue Wed Thu Fri Sat
- - 14:00 – 20:00 14:00 – 20:00 14:00 – 20:00 14:00 – 20:00 14:00 – 20:00
- - - - - - -

Supporter timezone: Asia/Ho_Chi_Minh (GMT+07:00)

Este tema contiene 22 respuestas, tiene 2 mensajes.

Última actualización por Beda hace 7 años.

Asistido por: Beda.

Autor
Mensajes
#582836

I am trying to: automatically update child calculated values when parent values change using php

Link to a page where the issue can be seen:

I expected to see: the child post data been calculated after I save the parent post

Instead, I got: no change in the child post

I use the following code:

// calculate life insurance need
function calculate_li_need($post_ID)
{
    if (get_post_type($post_ID) == 'life-insurance-need') {
//my calculations are here and they work
}
}
add_action('save_post', 'calculate_li_need', 99);


// Update child posts after parent post change
function update_child_posts($post_ID)
{
    if (get_post_type($post_ID) == 'net-worth') {
        //get parent post id
        $postid = $post_ID;

        //update life insurance child post
        $ret_childs_args = array('post_type' => 'life-insurance-need');
        $ret_child_array = get_posts($ret_childs_args);
        foreach ($ret_child_array as $ret_post_id) {
            $re_child_id = $ret_post_id->ID;
            $calculate_li_need($re_child_id);
        }
    }
}

please advise,
thanks,

David

#582939

This is Custom Code, that we cannot assist.

Let me explain why:

1. It uses no API of Toolset
2. It uses no Fields, or contents of Toolset
3. It applies common WordPress API on a Toolset Post Type.

Toolset is designed to avoid PHP writing.
I unterstand that sometimes you need to add functionality to it.

I cannot provide you a working code or help you deeply in the issue - but I can try to help you get to the goal with the code and your description of the task.

1. You have a Parent and a Child Post Type.
2. In the Child Post Type, you have some Fields, and with them, you would like to perform some calculations, so to probably update another value somewhere.
3. This actions on the Child Post should happen when the related Parent Post gets saved (updated).

I hope I did get the task correctly, otherwise please correct me.

So, you can do 2 things:
- use the WordPress API as you did (backend)
- or you can use the CRED API (frontend)
https://toolset.com/documentation/programmer-reference/cred-api/

In either cases, you need to start with the Parent Post Type (when it is saved/updated).

When that happens (save_post of your parent post type), you need to get a list of Child Posts (get_posts of child post type)

This list of Child Posts needs to be refined. You need only the posts that belong to the current Parent Post that is being saved.
So you will get_posts of Child Type with Custom Field "_wpcf_belongs_{your-parent-post-type-slug}_id" and value equal to the Parent Post ID (which is currently saved)

This will give you all Child Posts belonging to that parent.
Now, you can start to use wp_update_post() for those Child Posts:
https://codex.wordpress.org/Function_Reference/wp_update_post

You will of course have your values to calculate, and then you can wp_update_post() those results to another place.

I suggest to create a function for the calculations, a function for updating the child posts, and a function to hook into the save_post of the parent.
So you can subsequently call all the functions - it makes it easier to control and write.

Your current code presents a few errors, I think, specially how you get the parent post ID and the function to calculate the values.

#583169

Hi Beda,
I understand,

I was able to modify my code to:

//update child post
        $ret_childs_args = array('post_parent' => $post_ID, 'post_type' => 'life-insurance-need');
        $ret_child_array =  get_children($ret_childs_args);
        foreach ($ret_child_array as $ret_post_id) {
        	$re_child_id = $ret_post_id->ID;
		do_action( $calculate_li_need($re_child_id));

I'm not sure about my foreach statement. is it correct to use 'do_action( $calculate_li_need($re_child_id));' to call the calculation function of the child post? and do I need to put the child post id inside the function ()?
Or should I use 'wp_update_post ($re_child_id);

any help here will be great. I rather update child post automatically rather then going to each child post to click the update button...

BTW
I have a function to calculate the parent post, a function to calculate the child post. I just want to be able to call the child function calculation when I save the parent post.
I use 'cred_save_data' to hook to the calculation function when the posts are updated using the front end.

I also, looked at https://toolset.com/forums/topic/cpt-post-fields-save-ocuurs-after-wp_insert_post_data/#post-300311
it seems that there is something like:
function wpcf_pr_admin_save_post_hook( $parent_post_id )
that can update the child post by doing a save post on them
is this function exists?

please advise,
thanks,

David

#583935

You use now the attribute "post_parent".

This is irritated to Toolset relationships. It reflects Parent Pages set by WordPress.

As elaborated in Toolset Types parent Posts are stored with a Custom Field, as explained here:
https://toolset.com/forums/topic/automatically-update-child-calculated-values-when-parent-values-change-using-php/#post-582939

To call PHP functions in your Code, you simply call the function_name();

This will execute that function.

do_action() is a WordPress proprietary function that is not related to PHP but instead is created by WordPress to make things simpler.
https://developer.wordpress.org/reference/functions/do_action/

Yes, those hooks exist you list in the other ticket. But they are not Public API.
I suggest to use the WordPress API. Toolset Types API is often just a wrapper for it.

I suggest to hook in save_post() and get it's child posts - then update them or run the function you need.

#584606

ok,,
this is what i came with but it doesn't work for me.

function calculate_fields( $post_ID ) {
     
    if ( get_post_type( $post_ID ) == 'net-worth' ) {

// some calculation come here

// find child post of life-insurance-need type
$child_posts = types_child_posts("child-post-slug");
		foreach ($child_posts as $child_post) {
				calculate_li_need (); // call to calculate the child post function
			}

}    
}

// back end save parentpost
add_action( 'save_post', 'calculate_fields', 99 );

// front end save parent
add_action('cred_save_data', 'net_worth_calc',10,2);
function net_worth_calc($post_id, $form_data) {
	// if a specific form
    if ( $form_data['id'] == 9999|| $form_data['id'] == 9991) {
		calculate_fields( $post_id );
	}
}

// child post calculations
function child_post_calc( $post_ID ) {
     
    if ( get_post_type( $post_ID ) == 'child-post' ) {
//run calculation here
}   
}
//front end child post save (similar code as above just point to the child post function
...

any thoughts?

David

#584744

Let me go over your code.

function calculate_fields( $post_ID ) { //OK
      
    if ( get_post_type( $post_ID ) == 'net-worth' ) { //OK
 
// some calculation come here //OK
 
// find child post of life-insurance-need type
$child_posts = types_child_posts("child-post-slug");//please change "child-post-slug" to the real child posts type slug: https://toolset.com/documentation/customizing-sites-using-php/displaying-child-posts/
        foreach ($child_posts as $child_post) {
                calculate_li_need (); // call to calculate the child post function //OK you are in the single Post Object here. Keep in mind $child_post is NOT the ID but the entire Post Object.
            }
 
}    
}
 
// back end save parentpost
add_action( 'save_post', 'calculate_fields', 99 );
 
// front end save parent
add_action('cred_save_data', 'net_worth_calc',10,2);
function net_worth_calc($post_id, $form_data) {
    // if a specific form
    if ( $form_data['id'] == 9999|| $form_data['id'] == 9991) {
        calculate_fields( $post_id );
    }
}
 
// child post calculations
function child_post_calc( $post_ID ) {
      
    if ( get_post_type( $post_ID ) == 'child-post' ) { // You cannot compare a Post Type slug with an ID. Here you need to either pass the ID or change the compared property.
//run calculation here
}   
}
//front end child post save (similar code as above just point to the child post function
...

Please see my inline comments.

I think there need to be a few more adjustments. Please find also more information about the PHP and WordPress API here:
https://developer.wordpress.org/reference/functions/get_post_type/
https://toolset.com/documentation/customizing-sites-using-php/displaying-child-posts/

We have a great PHP documentation and examples gathered here:
https://toolset.com/documentation/customizing-sites-using-php/

We do not provide Custom Code, but with those examples you will see all possible approaches to handle Toolset data with PHP.

#585685

Thanks Beda,

my code above is just an example of how I thought its should be.
in my real code I have the correct slug...

the issue I have is whether or not I need to pass the child post ID into the function when I'm calling the function that updates the child post.
in your comment:
"calculate_li_need (); // call to calculate the child post function //OK you are in the single Post Object here. Keep in mind $child_post is NOT the ID but the entire Post Object."

I understand that this is an array of results for the post so I guess I need to pass the child post ID in to the function I call.
how can I do that?

I guess in the array results foreach get the child post ID and call the function:

foreach ($child_posts as $child_post) {
$child_post_id= $actual_post_id->ID;                
calculate_li_need (ID-> $child_post_id);
}

am I on the right track?

David

#585757

You will receive the ID from the Post Object.
This is for example:

$my_id = $post_object->ID;

Then, if you have a function that takes arguments, and expects this argument to be the Post ID, then you can call that function now with:

my_function_with_arguement($argument);

Where $argument is in our code example case "$my_id"

#586112

Thanks Beda,

i have modified the function as follow

// find child post of life-insurance-need type
		$child_posts = types_child_posts('life-insurance-need');
        	foreach ($child_posts as $child_post) {
			$child_id = $post_object->ID;               
			calculate_li_need ($child_id);
		}

but it doesn't work,
i know i'm close but need some help...

David

#586209
 $child_id = $post_object->ID;               

This is wrong, because you need to replace $post_object with the right variable (in your case probably $child_post)

Then, I do not know what does not work, and I not know what your function where you plan to pass the post id does.
You mentioned that is a working calculation, hence if that function needs the Post ID then you can pass it like that.

This is custom code, that seems to not work due to more custom functions that need a revision.
If you need help with this I suggest to contact someone here:
https://toolset.com/contractors/

Thank you!

#587378

Hi Beda,

Yes,
I used the correct code with:

 $child_id = $child_post->ID;  

as followed,

 
// find child post - life-insurance-need type and update
        $child_posts = types_child_posts('life-insurance-need');
            foreach ($child_posts as $child_post) {
            $child_id = $child_post->ID;               
            calculate_li_need ($child_id);
        }

the above code is firing something but its not working as intended, allow me to explain,
when I subtract a value (change the value of a field) in the parent post click save post and than refresh the child post the values in the child post updated i.e. doing somthing
however, when I add a value in the parent post, save it and refresh child post the updates doesn't happen.

please note that I'm listed on the https://toolset.com/contractors list under https://toolset.com/contractors/dazo-networks-llc

I really need help here. I reached out to the WordPress community and submitted a request on the vendor list for help but I think the only team that can really tackle this is the toolset team. please escalate to someone who can help with this.

Thanks,

David

#587502

So it seems when you update the post meta the code that updates your Child Post works.
When you add new Field values (previously empty) it does not.

The code I know from you is not responsible for this misbehave.
All you do with our API is get the Child Posts, and it's object data.

The code that does not work is your function calculate_li_need ($child_id);, since there is no other check in place in the rest of the code.

We cannot provide Custom PHP code.
https://toolset.com/toolset-support-policy/

For this, we exactly recommend the contractors listed here:
https://toolset.com/contractors/

I can try to have another look at your code, please show me the whole code and when, what and where you do to fire or use it.

I can then see if there is a logical problem or a problem with our API.

#587696

Thanks Beda,
can I send it to you via private message?
I dont want the code to be exposed...

Thanks,

David

#587927

I activated a private reply.

#588455

On the log in I receive:

Diese Seite funktioniert nicht
staging.davidzohar.com kann diese Anfrage momentan nicht verarbeiten.
HTTP ERROR 500

I cannot debug 100 lines of code for you, I am sorry.
We do not provide Custom Code, and review of such code is above the scope of support.

One thing I wanted to mention about the save_post() action with Toolset Post Types:
you need a minimal priority of 15, better 20, to use it with our Post types.
https://toolset.com/documentation/customizing-sites-using-php/updating-types-fields-using-php/

Eventually that is the problem you experience?