How to Keep Formatted Content with WordPress’ ‘get_post_meta’

Development

If you’re a WordPress developer, creating custom themes from scratch, you’ve been there before. You need to use custom fields in order to make for an easy content management experience on the admin side, but pulling content from custom fields on certain posts and pages into other page templates can be quite a tricky process – and keeping formatting is even harder.

Well, it was harder.

Problem:

WordPress, out-of-the-box, strips formatting on content when pulling from custom fields with ‘get_post_meta’. This isn’t good – custom fields are super handy for complex page layouts.

Solution:

  1. Add the following code to your ‘functions.php’ file. This recreates the default WordPress filters on content.
    <?php 
    
        /* @Recreate the default filters on the_content so we can pull formated content with get_post_meta
        -------------------------------------------------------------- */
        add_filter( 'meta_content', 'wptexturize'        );
        add_filter( 'meta_content', 'convert_smilies'    );
        add_filter( 'meta_content', 'convert_chars'      );
        add_filter( 'meta_content', 'wpautop'            );
        add_filter( 'meta_content', 'shortcode_unautop'  );
        add_filter( 'meta_content', 'prepend_attachment' );
    
    ?>
    
    

    See the Pen ubhsk by Keyfer Mathewson (@keyfermath) on CodePen.

  2. I presume by this point, you’ve already created and populated your custom fields, but you’re struggling with formatting that content. Take this custom field and save it as a PHP variable, using ‘get_post_meta’. Use this code in your theme’s custom page template file. If you’re unfamiliar with the ‘get_post_meta’ function, get your knowledge on here.
    <?php
    
    $unformatted_content = get_post_meta($postID, 'custom-field-name', true);
    
    ?>

    See the Pen ejIoC by Keyfer Mathewson (@keyfermath) on CodePen.

  3. The last step is to run this unformatted code through the filters we made in step one! Easy peasy.
    <?php
    
    $formatted_content = apply_filters('meta_content', $unformatted_content);
    
    ?>

    See the Pen oeFvB by Keyfer Mathewson (@keyfermath) on CodePen.

  4. Now you’re all set, you can echo that, or do whatever your heart desires!

If you have a WordPress problem you’d like an article on, let us know on Twitter!

Related Posts