Table of Contents
ToggleOverview
In this article I'll show you an easy way to insert clean, unformatted code – such as PHP, custom CSS, Javascript, etc. – into your WordPress posts or pages without using plugins or external code sources. Both WordPress plugins and 3rd party embeds like Pastebin add scripts to your site, which conflicts with running a fast and lean site and in this case, just isn't necessary. 🙂
Problem
My team and I had a problem when posting code snippets on our WordPress site for illustration or tutorial purposes. WordPress by default changes single and double quotes to more stylish, slanted quotes. They may look similar but they are different from the vertical quotation marks that appear in unformatted, plain text. Since they are different characters, they have the propensity to produce errors and even crash your site if used in a PHP file like functions.php.
So we had to find a way around this, but we did not want to use external sources or plugins for that since it creates loading overhead and we're all about great WordPress performance and load times.
Solution
We found a good and easy solution everyone can use, and I will show you how to do it. In our case we're using the Divi theme on our site (we use it on most all of our professional projects) but you don't have to have Divi to use this method.
- Open your post/page editor and make sure you are in Visual tab.
- Paste your code where you want to display it.
*Note: We are pasting our code here so that wordpress filters all our special characters for us. - In the right upper corner switch to Text tab.
- Wrap your code in <code> </code> tag.
- You can also indent it with <blockquote> </blockquote> tag:
<blockquote>
YOUR CODE GOES HERE
<code></code>
</blockquote>
That's it, now you have clean preformatted (or rather, UNformatted) code that you can paste on your site without bogging it down with scripts!
Alternative solution
Also, there is a nice online tool which we use to highlight code syntax for PHP, HTML, CSS and JavaScript code. Just click here and you will land on the main web page where you can just paste your code to highlight syntax.
Then click on “Highlight” and the online tool will generate a nice html code with inline CSS:
And here's the live code:
<?php
$str = “<h1>This is MemberFix</h1>”;
$newstr = filter_var($str, FILTER_SANITIZE_STRING);
echo $newstr;
?>
Questions, comments, concerns? Leave your thoughts in the comments below. 🙂