Im trying to change the title of a post, but I want to include info from a meta field, the value of which isn't saved to the database until after the posts has already been saved. Other than this one thing, it's working fine as a wp_insert_post_data
filter.
// add_filter('wp_insert_post_data', 'tr_change_show_title', 99, 2);
function tr_change_show_title($data, $postarr)
{
if('post' != $data['post_type']) {
// don't bother if its an auto-draft, as the post title may not have been completed yet, or in the trash
if ( !in_array( $data['post_status'], array( 'auto-draft', 'trash' ) ))
$child_ID = $postarr['ID']; // Child post id
$parent_ID = get_post_meta($child_ID, "_wpcf_belongs_booking_id", true); // parent ID
$post_type = $data['post_type'];
if ($post_type == 'show' && get_post_type($parent_ID) == 'booking') {
$parent_title = get_the_title($parent_ID);
$data['post_title'] = $parent_title; // save the parent title first
}
if (function_exists('types_render_field')) {
//this isn't working as the meta field isn't saved yet
$show_time = types_render_field( "show-time", array("post_id"=>"$child_ID", "raw"=>"true") );
if ($show_time){
$data['post_title'] .= ' : ' . $show_time; // Append Show time to title
}
}
$data['post_title'] .= ': show-' . $child_ID; // add the original post id
}
return $data;
}
I have read the codex, and this wpse post: https://wordpress.stackexchange.com/a/54713/13551 https://codex.wordpress.org/Function_Reference/wp_update_post
What I understand is that a infinite loop is a risk. To avoid this, we unhook and then rehook the save_post
before and after the meat of our work. Ive come up with the following, but dont quite understand why Im still running into an infinite loop.
add_action( 'save_post', 'tr_save_post_show_title', 99 );
function tr_save_post_show_title($post_ID){
if ( !wp_is_post_revision( $post_ID ) ) { // do nothing if a revision
// Prevent infinite loop
remove_action('save_post', 'tr_save_post_show_title');
// Add our filter
add_filter('wp_insert_post_data', 'tr_change_show_title', 99, 2);
write_log(array( 'ID' => $post_ID));
// Re-save the post this time with filter
wp_update_post( array( 'ID' => $post_ID), true ); // true for error catching
// Catch errors
if (is_wp_error($post_id)) {
$errors = $post_id->get_error_messages();
foreach ($errors as $error) {
write_log($error);
}
}
// re-hook the save_post action
add_action('save_post', 'tr_save_post_show_title');
}
}