Appending meta value onto post content in WordPress during save_post

The problem seems pretty straight forward: Once the save_post action is fired, I would like to append the value of a meta key onto the end of the post_content if it’s not already found within the post itself.

I’ve attempted making a call to wp_update_post() from within a function tied to save_post, but as many of you will immediately object, wp_update_post() contains do_action('save_post') and as such creates an infinite loop.

Read More

What other way (using the API) exists for one to update the content of a post based on said posts custom values once the post has been saved/edited without invoking a nightmarish infinite loop?

Related posts

Leave a Reply

1 comment

  1. 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)…”