Multiple lines of code indented in WordPress Comments

If you want to show and mark up a single line of code in your HTML just use the code tags, however with multiple lines you need to surround the code tags with pre tags.

In WordPress comments, pre tags are not allowed by default (externally) no matter if you write them, WP will remove them. You need to add a hook to the end of your funtions.php file (Apparence/Theme Editor)


// Create function which allows more tags in comments
function allow_html_attributes_in_comment() {
  global $allowedtags;
  $allowedtags['pre'] = array('class'=>array());
}
 
// Add WordPress hook to use the function
add_action('init', 'allow_html_attributes_in_comment', 11);

This will let your users to happily post their indented code 🙂

6 replies
  1. japanfever
    japanfever says:

    really? let’s see…

      
    function split1(str, del) {
        let arr = [];
        let piece = "";
        for (let i = 0; i < str.length; i++) {
            let j = 0;
            while (j < del.length && (i + j) < str.length && str[i + j] == del[j])  j++;
            if (j == del.length) {
                arr.push(piece);
                piece = "";
                i += j - 1;
            } else {
                piece += str[i];
            }
        }
        arr.push(piece);
        return arr;
    }
      
    
      • ggarcia
        ggarcia says:
          
          const people = [
            { name: 'Alice', age: 42 },
            { name: 'Bob', age: 116 },
            { name: 'Car', age: 15 }
          ]
        
        
          // Grouping objects by a property
          function groupBy(array, property) {
            return array.reduce((acc, obj) => {
              const key = obj[property]
              if (!acc[key]) 
                acc[key] = []
              
              acc[key].push(obj)
              return acc
            }, {})
          }
          
          const groupedPeople = groupBy(people, 'age')
          
        
      • Génesis
        Génesis says:

        I have erradicated your frustration forever, it was the fucking WordPress as you said. It was removing the pre tags from any external comment. I added a hook to the functions.php to fix it and now it’s working. Ctrl + F5 to see the post updated. I commented copying the code from the example and it keeps the indentation.

  2. japanfever
    japanfever says:

    i’ll try again:

    
    function split1(str, del) {
        let arr = [];
        let piece = "";
        for (let i = 0; i < str.length; i++) {
            let j = 0;
            while (j < del.length && (i + j) < str.length && str[i + j] == del[j]) j++;
            if (j == del.length) {
                arr.push(piece);
                piece = "";
                i += j - 1;
            } else {
                piece += str[i];
            }
        }
        arr.push(piece);
        return arr;
    }
    

Comments are closed.