I’ve searched around but I can’t quite pin down the answer for this. I am attempting to use the content of a custom field as post_data and save it to the database as such when a post is created or updated. I need to do this in order to make a frontend posting solution work out using the plugin Advanced Custom Fields.
I think I need something like this:
function tsv_content_save_pre( $post_id ){
global $post;
$tsvpost = get_post($post_id);
$tsvifempty = $tsvpost->post_content; //The "real" post_content
$tsvcontent = get_field('article_content'); //The custom content
if ($tsvifempty == NULL) { //Check if the "real" post content has anything in it first.
$tsvargs = array('post_content' => $tsvcontent);
wp_update_post ($tsvargs);
}
}
add_filter('content_save_pre' , 'tsv_content_save_pre' );
But I’m stuck there. I’m not a plugin developer so filters and such are hard for me to navigate. Can anyone help get me pointed in the right direction?
Thanks in advance.
First,
content_save_pre
is a very old hook. Adam Brown has a warning that:I would suggest a solution similar to one I proposed for a question asking about restricting status changes based on content word count.
Following your code very closely, the solution should look like this:
But I have concerns:
get_field
will work in that contextget_field
it looks like the function pulls data from the database, so it isn’t going to do you any good for updating a post– well, unless you update the post and the postmeta and then run another query to alter the post data, which seems profligate. And your question does specify “before writing to database”.So instead of the above, I think I would parse the
$_POST
data directly.Still more caveats:
wp_kses
article_content
— the last one, and only the last one, will be used.I think you need to have a post ID in your arguments array. From the doc:
OK, via WPQuestions.com I was able to get someone to figure this out. It requires 2 functions, 1 to handle posting on the front-end and another to handle posting on the back-end. Because ACF uses a custom function called acf/save_post instead of WP native save_post there was some extra work involved.
Here is the final working solution:
Hopefully this helps someone trying to do something similar!