WordPress – how to display code from a file in textarea

Using textarea in wordpress can cause lot of issues as wordpress automatically converts newlines to line-break (<br>) and paragraph (<p>) tags. Often switching from text to visual editor can also mess up formatting. Here is the workflow which I found worked best for me.

  1. Install wpautop-control wordpress plugin. This plugin lets you switch on and off wpautop per post or page.
  2. You may have to enable show custom field option (if not already) as shown:
  3. In the posts where you want to use textarea, disable wpautop by setting the custom field “wpautop” to false
  4. Now to include source code from a file (or some other text) in the textarea, The following plugin code can be used:
    function include_my_code ($atts) {
      extract(shortcode_atts(array('my_code_file' => ''), $atts));
      if ($my_code_file) {
        $content = file_get_contents($my_code_file);
        $content =  htmlentities($content);
      return $content;
    add_shortcode('include-my-code', 'include_my_code');

    To use this in wordpress (e.g. within textarea field) just include this in your post:

    <textarea>[include-my-code my_code_file="some_path/somefile.txt"]</textarea>

    Note that the path should be either absolute path or relative to WordPress root dir.

Security notes

This shortcode will allow anyone to display any file from the server in a post. If this is a concern, you can allow only specific directory/directories in shortcode php.

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


Click here to write/view comments