Here is what I am trying to do – I have created a custom table in the database and I am trying to enter data into it everytime a post is created. The database-entry needs to happen ONCE AND ONLY WHEN A NEW POST IS CREATED. NOT on post-update, revision, status-change etc. FYI, new posts created are always put to draft
status and then published later. Data that is inserted into the table is metadata of the created post, that is a post-meta-key and its post-meta-value. I need this custom data to be in a separate table.
This is what I have tried -
I am not sure what specific wp-hook I should be hooking into to perform this function. After some research here is some code that I have cooked up, that uses wp_insert_post()
.
function update_profile_record( $post_id ) {
//if ($post->post_type = 'post') return;
$pro_realname = get_post_meta( $post_id, 'realname', true );
$pro_cell = get_post_meta( $post_id, 'cell', true );
$pro_email = get_post_meta( $post_id, 'e_mail', true );
$pro_subdate = get_post_meta( $post_id, 'submit_date', true );
if ($pro_subdate == '') { $pro_subdate = get_the_date( $format, $post_id ); }
global $wpdb;
$table_name = $wpdb->prefix . "profile_record";
$wpdb->insert( $table_name, array(
'rec_profile_name' => $pro_realname,
'rec_profile_contact' => $pro_cell,
'rec_profile_email' => $pro_email,
'rec_profile_date' => $pro_subdate
));
}
add_action( 'wp_insert_post', 'update_profile_record', 10, 1 );
UPDATE
Here is what is happening – This code using wp_insert_post
helps make entries into database without a hitch, the problem is everytime any post is updated, a duplicate entry is inserted into the db. The solution provided by @s_ha_dum in the answer results in empty values in the custom table.
According to post transition status, I have also tried {auto-draft}_to_{draft}
, {new}_to_{draft}
, {new}_{post}
but it does not fill up any data in the table. So my question is, is there a specific hook for the function I am trying to achieve or I will need to rely on save_post/wp_insert_post
only alongwith if_else statements.
Here is the order of how it needs to happen :
- A new post is created and put to draft status, alongwith the custom meta data ( Metadata is now available in the DB, so now it is available to be copied to custom table in DB ).
- Once metadata is available, our function runs and updates the values to custom table.
If I am not wrong here, looks like my function needs to run just after the post is created, needs to run only once and should not be affected with any sort of post updates.