Home›Toolset Professional Support›[Resolved] How to duplicate content from Types fields in standard post body and excerpt fields
[Resolved] How to duplicate content from Types fields in standard post body and excerpt fields
This thread is resolved. Here is a description of the problem and solution.
Problem:
Client has a form where the user does not enter the post body or excerpt for a post and instead fills some Types fields that the client would like to use to populate the standard post fields with duplicated content when the post is saved.
I would like not to show the default post editor and excerpt textarea, but have Toolset fields so I can describe the expected content. But for newsletters, etc. to work, I need to have the excerpt and post content end up with data in them.
To give an example: I want my Toolset field "Home Page Tease" to be saved as the post excerpt. I want my "Discussion" WYSIWYG field and my map image to be merged into the post content. But I don't want that data doubled up in the database.
Are your users adding content in the backend or using CRED front-end forms?
What I advise will depend on that.
Regarding having the content stored in the database twice, that is probably inevitable, except in the case where your users never edit their content once submitted. Do you require them to be able to edit it?
Thinking about it some more, I don't mind the content being duplicated. That will allow use of the default fields in the places plugins expect it, while using the Toolset fields for display on the site.
Writing custom code falls outside of our support policy, but I'll give you the basics of what you require here because there are a few gotchas such as avoiding infinite loops. I'll leave you to modify the code to your requirements, but it you get stuck let me know.
function tssupp_update_post_fields( $post_id, $post ){
$post_type = 'post'; // Edit for post type slug
$body_field = 'discussion'; // Edit slug of field to copy to body
$excerpt_field = 'home-page-tease'; // Edit slug of field to copy to excerpt
if ( is_admin() && $post->post_type == $post_type && $post->post_status != 'auto-draft' ) {
$update = array(
'ID' => $post_id
);
// Get the excerpt field to update the excerpt
if ( isset( $_POST['wpcf'][$excerpt_field] ) ) {
$update['post_excerpt'] = $_POST['wpcf'][$excerpt_field];
}
// Get the body field to update the body
if ( isset( $_POST['wpcf'][$body_field] ) ) {
$update['post_content'] = $_POST['wpcf'][$body_field];
}
// Update the post
// First unhook this function to avoid infinite loop
remove_action( 'save_post', 'tssupp_update_post_fields', 10, 2 );
// Update
wp_update_post( $update );
// Re-hook this function
add_action( 'save_post', 'tssupp_update_post_fields', 10, 2 );
}
}
add_action( 'save_post', 'tssupp_update_post_fields', 10, 2 );