I have a plugin with several CPTs (we’ll call them CPT-A, CPT-B, CPT-C, and CPT-D). All CPTs have custom fields. In CPT-D, the user is able to make a selection and assign a post in CPT-A, CPT-B, and CPT-C to the current post in CPT-D. Basically linking relevant records to each other.
If the post in CPT-A, CPT-B, and/or CPT-C does not yet exist, the user can “quickly” create the post by entering the post’s title using a standard text input field. No other data is required, and any optional data can be entered later.
I then will use wp_insert_post() to add the new post (CPT-A, CPT-B, and/or CPT-C). This all works as expected.
Next, I need to update CPT-D’s postmeta with the post ID of the new CPT-A, CPT-B, and/or CPT-C. To do this, I am using update_post_meta().
The problem I’m having is that the wrong post’s postmeta is being updated.
For example, if CPT-D’s Post ID is 99, it should have postmeta meta_key ‘assigned-cpt-a’ = 100, ‘assigned-cpt-b’ = 101, and ‘assigned-cpt-c’ = 102 if all three CPT’s are set.
What happens instead is:
CPT-D gets postmeta ‘assigned-cpt-a’ = 100
CPT-A gets postmeta ‘assigned-cpt-b’ = 101
CPT-B gets postmeta ‘assigned-cpt-c’ = 102
Here is a sample of the code that inserts the new CPT and updates postmeta:
<?php
$new_cpta_title = sanitize_text_field( $_POST[ 'cpt-a-name' ] );
/* Only add new if a CPT with the same title doesn't already exist */
if( null == get_page_by_title( $new_cpta_title, OBJECT, 'cpt-a' ) ) {
$new_cpta_slug = preg_replace("/[^A-Za-z0-9]/",'',strtolower($new_cpta_title));
$author_id = get_current_user_id();
$new_cpta = array(
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_author' => $author_id,
'post_name' => $new_cpta_slug,
'post_title' => $new_cpta_title,
'post_status' => 'publish',
'post_type' => 'cpt-a'
);
wp_insert_post( $new_cpta );
$new_cpta_info = get_page_by_path($new_cpta_slug, OBJECT, 'cpt-a');
if ( $new_cpta_info ) {
$new_cpta_ID = $new_cpta_info->ID;
update_post_meta( $post_id, 'cpt-a-id', $new_cpta_ID );
}
}
So, my question is, how can I reset the $post_id in update_post_meta to be the same post ID as the original CPT-D?