Appending meta value onto post content in WordPress during save_post

The initial solution I’ve found is to tie a filter onto an action like wp_insert_post_data and extract other post information from the global $post object.

// Tack our filter onto the wp_insert_post_data action
add_filter( 'wp_insert_post_data', 'my_appender' );
function my_appender( $content ) {
  // Bring global $post into scope
  global $post;
  // Get meta value of meta key 'key_name'
  $meta_value = get_post_meta( $post->ID, 'key_name', TRUE );
  // If value is not in content, append it onto the end
  if ( stristr( $content['post_content'], $meta_value ) === FALSE )
    $content['post_content'] .= $meta_value;
  // Return filtered content
  return $content;
}

I’m certain this could see improvement.

References

  1. add_filter() – “Filters are the hooks that WordPress launches…”
  2. wp_insert_post_data – “A filter hook called by the wp_insert_post function…”
  3. global keyword – “The scope of a variable is the context within which it is defined…”
  4. get_post_meta() – “This function returns the values of the custom fields…”
  5. stristr() – “Find first occurrence of a string (Case-insensitive)…”