How can I code to insert/update/delete repeatable field and associate to specific custom post?
Hi,
Thank you for contacting us and I'd be happy to assist.
For repeatable fields where multiple instances of values are allowed, you can use the 'add_post_meta' function, with the 'unique' parameter set to 'true':
https://developer.wordpress.org/reference/functions/add_post_meta/
This way each new value will be saved as a new entry and won't overwrite the existing custom field values.
regards,
Waqar
Dear Waqar,
Could you please explain how I can get the correct $meta_key, $meta_value if my repeatable group slug is ecard-contact-group and field slug is contact-type and how do I update the title of each rfg ? Giving me the sample code is appreciated.
Thanks for writing back.
I thought you were referring to the repeatable field, but from the screenshot, you're clearly using the repeatable field group.
The fields in the repeatable field group are stored with a separate hidden post type connected through a one-to-many post relationship with the parent post type.
Can you please share the temporary admin login details of the website, along with the exact place where you're planning to use this code? I'll be in a better to suggest a code example, accordingly.
Note: Your next reply will be private and making a complete backup copy is recommended before sharing the access details.
regards,
Waqar
I rewrite my code as below and work
$post_id = 9;
printf("post_id: %s<br/>", $post_id);
// create repeatable group
$new_post_id = wp_insert_post(
array(
'post_type' => 'ecard-contact-group',
'post_title' => "pending rfg for $post_id",
'post_status' => 'publish',
'meta_input' => array(
'wpcf-contact-type' => 'mobile',
'wpcf-content' => rand(10000000, 99999999),
)
)
);
printf("new_post_id: %s<br/>", $new_post_id);
wp_update_post(array(
'ID' => $new_post_id,
'post_title' => 'Mobile (Testing) - ' . rand(1000,9999),
'post_name' => $new_post_id
));
toolset_connect_posts('ecard-contact-group', $post_id, $new_post_id);
What is the problem? The first sample I insert post and add post_meta one by one and then build the relationship, the second is inserting the post all in one including the post_meta and then build the relationship, why the first one not work ?
I may want to check whether the rfg already existed before I do the add_post_meta(), can do?
Thank you for sharing this update and glad that you were able to sort it out.
In the first instance of the code, I don't see the post type being specified at the time of new post creation.
( post_type' => 'ecard-contact-group', )
You can fix it and then test the same code again.