Skip Navigation

[Resolved] save_post and custom field

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
- 9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 -
- 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 -

Supporter timezone: Asia/Hong_Kong (GMT+08:00)

This topic contains 4 replies, has 2 voices.

Last updated by andreaV-4 1 year, 9 months ago.

Assisted by: Luo Yang.

Author
Posts
#2554081

Hi,
I would like to update the title of my post (with some data taken from custom fields) after insertion and with each update. Using save_post the whole thing works with updates but on the first insert the custom fields always come up empty even though they are valorized (if I then do an update without any changes it works). How can I do this?

Regards

#2554107

Hello,

Please follow WP document to setup your custom PHP codes:
https://developer.wordpress.org/reference/hooks/save_post/

And I suggest you use a higher value for the "Priority" parameter, so it can be triggered after all other fields are saved into database, for example:
add_action( 'save_post', 'MY-CUSTOM-FUNCTION', 999 );

More help:
https://developer.wordpress.org/plugins/hooks/actions/#priority

#2554133

Hi Luo Yang,
thank you. Even setting as priority 999 the custom fields are not displayed.
To get the custom field I run this command

$date = types_render_field( 'date' , array( 'post_id' => $post_id ));

In the update it works but in the first save it does not.

Regards

#2554155

I have tried it in a fresh WP installation + the latest version of Toolset plugins, it works fine after you publish the post and refresh the browser, see below test site:
1) Login URL:
hidden link

2) Custom codes:
hidden link
Line 70~81:


add_action('save_post', 'my_function', 999, 3);

function my_function($post_ID, $post, $update){
  remove_action('save_post', 'my_function', 999);
  $date = types_render_field( 'date' , array( 'post_id' => $post_ID ));
  $my_post = array(
      'ID'           => $post_ID,
      'post_title'   => 'Post title - ' . $date,
  );
  wp_update_post( $my_post );
  add_action( 'save_post', 'my_function', 999, 3 );
}

3) Create a post, setup the date field value, publish and refresh your browser, I can see it works fine.

#2554215

My issue is resolved now. Thank you!