Update post if title exists, else create new post

I’m using Zapier to automate the posting of a WordPress page based on an outside trigger, and I would like to have WordPress update an existing post if the title matches an existing post title or add a new post if an existing post does not exist. I’m adding this function to functions.php to hook in with the save_post action, so if I should be doing this elsewhere, maybe that’s where I’ve gone wrong.

I had previously just used an if statement where it would whether get_page_by_title() evaluated as NULL, but for some reason it would always create the post first before checking get_page_by_title() so it would never go down the update pathway and I’d end up with duplicate posts. I tried to get around this by assuming the post had already been triggered and instead checking the timestamp on the post and if the prior post had a different timestamp, I’d assume I needed to update the post, then deleting the just-created post (I know, there’s got to be a better way).

Here’s what I’ve got so far. I’m using $existing_post to refer to the previous post that I didn’t just create and attempting to update the content of the existing post with the content of the newly-created post. I’m not getting duplicate posts any more but the content of the post isn’t being updated when I send over a new post with the same title and updated content:

function update_or_create_post( $post_id, $post ) {
if ( ‘publish’ === $post->post_status && $post->post_type === ‘my_custom_post_type’ ) {
$existing_post = get_page_by_title( $post->post_title, OBJECT, ‘my_custom_post_type’);
if ( $existing_post->post_date != $post->post_date ) {
$existing_post_id = $existing_post->post_id;
$new_post_content = $post->post_content;
$update_post_content = array(
‘ID’ => $existing_post_id,
‘post_content’ => $new_post_content,
);
remove_action ( ‘save_post’, ‘update_or_create_post’, 0, 2 );
wp_update_post( $update_post_content );
wp_delete_post ( $post_id );
add_action( ‘save_post’, ‘update_or_create_post’, 0, 2 );
}
}
}
add_action( ‘save_post’, ‘update_or_create_post’, 0, 2 );

Read more here:: Update post if title exists, else create new post

Leave a Reply

Your email address will not be published. Required fields are marked *