Change content before writing to database

First, content_save_pre is a very old hook. Adam Brown has a warning that:

This hook does not occur in the most recent version of WordPress
(3.5). Do not use it. It is deprecated. You should look at the list of
“related hooks” below to see if you can figure out what replaced it.

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:

function cmeta_as_content_wpse_92012($data){
  if (!empty($data['post_content'])) {
    $tsvcontent = get_field('article_content'); //The custom content
    $data['post_content'] = $tsvcontent;
  }
  return $data;
}
add_action('wp_insert_post_data','cmeta_as_content_wpse_92012');

But I have concerns:

  1. I don’t know if get_field will work in that context
  2. If I have found the right docs for get_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.

function cmeta_as_content_wpse_92012($data){
  global $_POST;
  if (!empty($data['post_content']) && !empty($_POST['meta'])) {
    foreach ($_POST['meta'] as $v) {
      if ('article_content' == $v['key']) {
        $data['post_content'] = wp_kses( $v['value'] ); // The custom content
      }
    }
  }
  // var_dump($_POST,$data); die; // debugging
  return $data; 
}
add_action('wp_insert_post_data','cmeta_as_content_wpse_92012',1);

Still more caveats:

  1. I can’t remember at which step WordPress applies its own filters, so I applied wp_kses
  2. Item #1 may be overkill
  3. Item #1 may not be the particular validation function you want
  4. If there are multiple custom meta fields with the same key– article_content— the last one, and only the last one, will be used.

Leave a Comment