Creating the content for a WordPress ‘help’ website like this, it’s very difficult to know where to start. One of the first things we wanted to do was to display various code snipets in our posts, and this can be tricky with some themes. So, if you were asking ‘How can I display code snippets in WordPress?” here is a simple and very quick answer..
Do the same as we do, and use Gist. As alternatives you could try JSFiddle or Pastebin.
Pasting code into a WordPress page is tricky
There are plenty of articles online explaining how to use ‘pre’ and ‘code’ to display your code. You’ll also find very simple instructions on how to create a plugin which will convert your code characters to HTMl entities, which should make WordPress display your code rather than run it. However, we’ve come across many themes (the one we use on this site is a great example) where this just doesn’t work. It’s not important why; it just doesn’t work.
Rather than mess about trying to work out what works (and doesn’t) on your website, save yourself hours of time and visit the Gist website, open a free account and create a ‘gist’. You’ll need to confirm your email before you get started.
Once you’re sorted, look on the main page and you’ll see ‘New gist’ at the top of the page. Click it. A new page will appear where you can write/paste your code and create what’s called a ‘gist’.
Give the code snippet a file name, so in our case example1.php. Write or paste your code into the main box. When you’re done, decide if this is a private or public snippet and click the relevant button. That’s it.
You’ll then see another page which confirms your gist has been created. Above the gist you’ll see a dropdown box where you can choose to embed or share the gist. Click ‘Embed’. Then click the ‘copy’ icon to copy the embed script. Go back to your website and paste the script into whatever page or post you like. That’s it.
In case you’re wondering, the example gist we created is pasted below, so you can see exacly what the final result is. It’s a simple bit of php we copied from one of our early websites which looks to see if a post (in a business directory) has an (optional) logo, and displays it if it does. If there’s no logo, then it displays an alternative (obligatory) image in its place.