Enter and display code snippets in WordPress custom fields

Published: August 15, 2014 | Last Modified: October 3, 2017

If you use a WordPress custom field to display code snippets like I do on this site, then you will notice that if you enter the full code with <\?php e.g.

<?php echo get_post_meta($post-&amp;gt;ID, 'custom-post-name', true); ?>

It will not display as you need to tell your template to escape the special characters. To do this add htmlspecialchars before the function like:

<?php echo htmlspecialchars(get_post_meta($post-&amp;gt;ID, 'custom-post-name', true)); ?>

and your code will display nicely.