Using WordPress custom field for displaying code

WordPress custom fields (post meta keys) can be used to store key value pairs for a post. This can be very useful to store code related to that post. This way it can be used by other pages also. Here are steps to use WordPress post custom field for storing and displaying code snippet.

Add post custom field

In wordpress post admin interface, add a custom field with key=code1 as shown below:
wordpress-custom-field-for-php-code-exampel

Plugin to read code from custom field and display it with pre

Now we can write a simple plugin to read the custom field and display it using html pre tag and html entities. Here is the code for it:

function handle_my_code ($atts) {
  global $post;
  $ret = "";
  extract( shortcode_atts( array(
    'key' => '',
    'postid' => $post->ID,
  ), $atts ) );
  if ($key) {
   $codeval = get_post_meta($postid, $key, true);
   $ret .= "<pre>" . htmlentities($codeval)  . "</pre>\n";
  }
  return $ret;
}
add_shortcode('my-code', 'handle_my_code');

Using the plugin

Use the following code to use the plugin and embed code from custom field in any post:

[my-code key="code1"]

Here is how it will appear on site:
wordpress-custom-field-php-code-display-using-pre

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments