Skip Navigation

[Resolved] How to calculate custom fields of child posts?

This support ticket is created 6 years, 11 months ago. 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.

Sun Mon Tue Wed Thu Fri Sat
- 12:00 – 17:00 12:00 – 17:00 12:00 – 17:00 12:00 – 17:00 12:00 – 17:00 -
- 18:00 – 21:00 18:00 – 21:00 18:00 – 21:00 18:00 – 21:00 18:00 – 21:00 -

Supporter timezone: Asia/Karachi (GMT+05:00)

This topic contains 13 replies, has 2 voices.

Last updated by Noman 6 years, 10 months ago.

Assisted by: Noman.

Author
Posts
#603287

Tell us what you are trying to do?

I want to calculate the custom fields of child posts.

My website is a directory for mining companies. This is the website structure.
Company (Parent)
- Mine (Child)

The goal here is to total up all the commodity of the company categorized by commodity.

The custom field of the child posts that I want to calculate is [types field='reserves-contained'][/types].

THE TRICKY PART here is calculating similar commodities. Because most companies have different commodities and we don't want to total up Gold with Silver or Copper with Iron, etc. We want to total up similar commodities.

The custom field for the commodity of each mine is [types field='mineral'][/types].

Any help would be great 🙂

#603335

Noman
Supporter

Languages: English (English )

Timezone: Asia/Karachi (GMT+05:00)

Hi Stanley,

Thank you for contacting Toolset support. Please confirm the below structure you have:

You have Company (Parent CPT) that have Commodity category and Commodity category have term field that have Gold, Silver and Copper mineral as values.

You have Mine (Child CPT) that have Reserves Contained custom field and they will have numeric values for minerals (Gold, Silver and Copper).

Now you want to display calculated result on Parent CPT single page?

For example:
Company post 1 have 3 child posts with 3 commodies (2 Gold and 1 Sliver term values).
We need to display 3 child posts (with 10, 20, 40 values respectively) calculated field result on Company post 1 single page will be like this:

Child post Gold value = 30
Child post Silver value = 40

Thank you

#603344

Hey Noman,

You're right on the CPT. For the parent commodities, I seprarate them into custom fields. Each commodity = one custom field.

For the child commodities, I separated them into each posts. A mine might have multiple commodities and each commodity = one post.
For example,
- Mine A Gold
- Mine A Silver

To identify the commodity, there is a custom field for that called "mineral"

Apologies if my structure isn't that efficient but it gets the job done so far.

#603464

Noman
Supporter

Languages: English (English )

Timezone: Asia/Karachi (GMT+05:00)

Hello Stanley,

Can you please provide temporary access WP-Admin Login and FTP login info to your site, I need to take a look at your setup and structure.

Can you please let me know where you want to display calculated result?

Your next answer will be private which means only you and I have access to it.

=== Please backup your database and website ===

✙ I would additionally need your permission to de-activate and re-activate Plugins and the Theme, and to change configurations on the site. This is also a reason the backup is really important.

✙ Please add the related back-end and front-end links or screenshots.

Thank you

#603797

Noman
Supporter

Languages: English (English )

Timezone: Asia/Karachi (GMT+05:00)

Thank you for providing login details. I am working on it and will get back to you soon.

Thanks

#603817

Noman
Supporter

Languages: English (English )

Timezone: Asia/Karachi (GMT+05:00)

Hello Stanley,

Here you can see result:
hidden link

We can achieve it using custom shortcode. I have added following function in functions.php file for Gold and Silver, you can add more minerals the same way:

add_shortcode('wpv_child_post_calculate', 'wpv_child_post_calculate_fun');

function wpv_child_post_calculate_fun($atts) {
	$parent_post_id = 0;
	
    extract( shortcode_atts( array(
		'parent_post_id' => $parent_post_id,
		'child_post_type' => 'mine', // child cpt slug
    ), $atts ) );
  
  	$parent_cpt_slug = get_post_type($parent_post_id);
  
	$child_posts_args = array( 'post_type' => $child_post_type, 'meta_query' => array(array('key' => '_wpcf_belongs_'.$parent_cpt_slug.'_id', 'value' => $parent_post_id))); // parent cpt slug
	$child_posts = get_posts( $child_posts_args );
	$gold_sum = $silver_sum = 0;
	$mineral = '';
foreach ( $child_posts as $post ) : setup_postdata( $post ); 
	
	$mineral = get_post_meta( $post->ID, 'wpcf-mineral', true );
	
	if( isset($mineral) && $mineral != '' ) {
		switch($mineral) {
			case 'Gold':
				$gold_sum += get_post_meta( $post->ID, 'wpcf-reserves-contained', true );
			break;
			case 'Silver':
				$silver_sum += get_post_meta( $post->ID, 'wpcf-reserves-contained', true );
			break;
		}	
	}
endforeach; 
wp_reset_postdata();
	
	if( $gold_sum != 0 )
		$content = ' Gold value = '.$gold_sum;
	if( $silver_sum != 0 )
		$content .= ' Silver value = '.$silver_sum;
		
	return $content;
}

Then used the following shortcode in Parent Post CT:

[wpv_child_post_calculate parent_post_id="[wpv-post-id]"]

Above shortcode working as follows:
- It get all child posts of current parent post.
- Then get ‘mineral’ custom field value from child posts.
- If mineral value is Gold or Silver then added in gold or silver variable.

Thank you

#603910

Thanks for the code, Noman. I have a few questions:
1. Are you calculating the child posts based on the parent id?

2. Can we calculate the child posts based of a custom field instead? Because right now I am waiting for the many-to-many relationship to be released and I'm using a custom field to find the child posts of a company.

3. How would you filter based on tags? The reason is because I have two types of child posts, (1) is based of resources / how much mineral is in the mine (2) is based of production / how much mineral is the mine producing.

The tags for child posts based of resources is "mine-minerals" and tags for mine production is "mine-production".

#603920

Ignore my #3 question because I don't think that won't be necessary anymore.

I have another question.
How would you put the calculation into a custom field in the parent post.
For example, put the sum of all gold into custom field "parent-gold-value", sum of all silver into "parent-silver-value".

#604363

Noman
Supporter

Languages: English (English )

Timezone: Asia/Karachi (GMT+05:00)

Hello Stanley,

1. Are you calculating the child posts based on the parent id?
>> Yes.

2. Can we calculate the child posts based of a custom field instead? Because right now I am waiting for the many-to-many relationship to be released and I'm using a custom field to find the child posts of a company.

>> Yes, we can calculate child posts based on custom field. Here is docs:
https://toolset.com/documentation/user-guides/creating-post-type-relationships/
https://toolset.com/documentation/customizing-sites-using-php/displaying-child-posts/

3. How would you put the calculation into a custom field in the parent post.
>> You need to create function that will add/update parent field value when child post add/update.
You can use following hook for it:
https://codex.wordpress.org/Plugin_API/Action_Reference/save_post

And function steps will be something like this:
- Get current post Parent ID
- Get all childs of selected parent as we did in wpv_child_post_calculate_fun
- Then calculate fields as we did in wpv_child_post_calculate_fun
- Then store calculated result in parent filed using update_post_meta function.
https://codex.wordpress.org/Function_Reference/update_post_meta

Thank you

#605888

Hey Noman,
Would you be able to write a code up for the functions above? Your previous one was really good.

#609376

Noman
Supporter

Languages: English (English )

Timezone: Asia/Karachi (GMT+05:00)

For some reason I lost your ticket and it didnt show up in my queue, I am going to review your request and get back to you.

Thank you

#609652

Noman
Supporter

Languages: English (English )

Timezone: Asia/Karachi (GMT+05:00)

Hello Stanley,

Code will be like this as I describe in Point 3:

function calculate_fields( $post_ID ) {
	
	if ( get_post_type( $post_ID ) == 'child-post-slug' ) { // If child post Create/Update
	
		// Get current post Parent ID
    	$parent_post_id = get_post_meta($post_ID, "_wpcf_belongs_parent_id", true);
    	
		// Get all childs of selected parent as we did in wpv_child_post_calculate_fun
		$parent_cpt_slug = get_post_type($parent_post_id);
   
    	$child_posts_args = array( 'post_type' => $child_post_type, 'meta_query' => array(array('key' => '_wpcf_belongs_'.$parent_cpt_slug.'_id', 'value' => $parent_post_id))); // parent cpt slug
    	$child_posts = get_posts( $child_posts_args );
    	$gold_sum = $silver_sum = 0;
    	$mineral = '';
		foreach ( $child_posts as $post ) : setup_postdata( $post ); 
			 
			$mineral = get_post_meta( $post->ID, 'wpcf-mineral', true );
			
			//Then calculate fields as we did in wpv_child_post_calculate_fun
			if( isset($mineral) && $mineral != '' ) {
				switch($mineral) {
					case 'Gold':
						$gold_sum += get_post_meta( $post->ID, 'wpcf-reserves-contained', true );
					break;
					case 'Silver':
						$silver_sum += get_post_meta( $post->ID, 'wpcf-reserves-contained', true );
					break;
				}   
			}
		endforeach; 
		wp_reset_postdata();
     
	 	// Then store calculated result in parent filed using update_post_meta function
		if( $gold_sum != 0 ) {
			
			// Total Gold
			update_post_meta( $post_ID, 'wpcf-parent-custom-field-for-gold', $gold_sum );
		}
		if( $silver_sum != 0 ) {
			// Total Silver
			update_post_meta( $post_ID, 'wpcf-parent-custom-filed-for-silver', $silver_sum );
		}
 
	}
	
}
add_action( 'save_post', 'calculate_fields', 99 );

>> Please update parent/child and fields slugs from above code

Feel free to let me know if you found any issue to implement above code.

Thank you

#610603

Thanks for the code, Noman. You're awesome!

I have another question. What if instead of calculating based on parent post ID, we change that to calculating based on a custom field?

The reason is because in some parent posts, the parent-child relationship is set by a custom field I created called wpcf-co-ticker-symbol.

Would that be possible?

#610708

Noman
Supporter

Languages: English (English )

Timezone: Asia/Karachi (GMT+05:00)

Hello Stanley,

Do you want to calculate only those child posts that parent don’t have empty value in ‘wpcf-co-ticker-symbol’?
If yes, then you can calculate.

Please kindly open a new ticket for each issue. This will help other users with similar problems to find solutions when searching the forum.
https://toolset.com/toolset-support-policy/

Thank you