Creating my first WordPress plugin and learning PHP

Firstly, I have to say that I was pleasantly surprised how easy it was to do both of these – that is, creating a simple WordPress plugin as well as learning from scratch enough PHP to do this. It still required some cognitive effort, but the whole ordeal was completed within an evening.

One of my tasks this weekend was sorting out my links page. I want to keep it looking fairly tidy and organised, so I used a table. Even the simple layout below took a fair amount of repetitive HTML in order to do this. If I wanted to make a change (e.g. widen one column) this would mean modify a value for every row. Not efficient!

old-links-page

The above table was made with code that looks like this:

old-links-page-2

Imagine the list grows and there are 50 rows in the table. Then I decide to add a new column. I would have to manually add every extra cell manually, which is not going to be fun.

PHP

PHP is a scripting language that you can use to automate repetitive parts of your code, among many other tasks. It’s incredibly powerful – it’s the language that powers WordPress after all. I wondered if it was possible to have a PHP script generate the HTML to make the table.

So I set about learning some PHP using the excellent PHP tutorial at w3schools. I’m not familar with JavaScript, but PHP is similar enough to C# that it was mostly a breeze.

When learning, I found it was useful to create a document on my server. I logged into cPanel and created a new document here to practise with. cPanel includes a code editor. Alternatively you could create a local document. Which in hindsight is probably simpler.

Incidentally, what is the key difference between PHP and JavaScript? PHP runs on the server and delivers the output (i.e. the HTML) over the internet. With JavaScript, the server sends the code itself to the client machine (i.e. your computer) and the code executes there. I learnt that today 🙂

First attempt with PHP in WordPress (Spoiler: It fails!)

The easiest solution would be to add a bit of PHP script within the HTML that makes up the links page. On my practice page I eventually managed to get a solution working in principle. Essentially all you do is create a function with arguments like ‘URL’ and ‘description’, and in that function you use the echo command to construct the HTML.

function AddLinksRow($URL, $name, $description)
{
echo '<tr>
<td><a href="' . $URL . '"><img src="https://eu2.searchpreview.de/preview?s=' . $URL . '" /></a></td>
<td><b><a href="' . $URL . '">' . $name . '</a></b></td>
<td>' . $description . '</td>
</tr>';
}

echo '<table class="JR">';
AddLinksRow("http://www.google.co.uk","Google","Search the web with google");
AddLinksRow("http://www.bbc.co.uk","BBC","News");
echo '</table>';

This makes the following table:

php-test

If you’re already familiar with HTML table notation, you should be able to see how the function is constructing the HTML, and the great thing about PHP is that we can effectively include variables in our HTML. So we can reuse the same function to generate a new batch of HTML for each row of the table.

By default, I use the HTML editor in WordPress. (Not a fan of WYSIWYG as often what I see isn’t what I get.) So you would think that copying the code over into a WordPress page would be trivial.

If only! Even the HTML editor still undergoes some ‘tidying’ by WordPress. This is why it’s possible to create new paragraphs with the return key without having to use <p> tags. One other thing that it does is block PHP execution. Instead, your page will make a token attempt of trying to render your script.

There is a range of plugins for WordPress that re-enable in-line PHP execution in posts and pages, such as Insert PHP or Shortcode Exec PHP. Frustratingly, none of these seem to work.

Digging in, many of these projects have not been updated in a while, and none of them profess to have support for version 4.x of WordPress. This seemed to be a dead-end.

Shortcodes in WordPress plugins

But then it occurred to me that WordPress plugins are written in PHP. Many plugins use shortcodes to allow the user to interact with them. For example, a plugin has been written to generate a list of saved links from the Pocket bookmarking service. You can see my list here. All I had to do to generate this list was type [pocket_links] in my page, and this shortcode would find the Pocket WP plugin, which in turn would fill out the page for me. These shortcodes can also take arguments, e.g. [pocket_links count=5] to display 5 items only from my Pocket list.

So, in principle, would it be possible to write an extension where I could write a shortcode with the URL and description as arguments, and let a plugin turn this information into a table row? Instead of that messy HTML above, could I write something much tidier like this?

[AddRow URL=”http://www.google.co.uk” name=”Google” description=”Search the web”]

Starting my first WordPress plugin

The process is remarkably simple. I followed this tutorial to get going, but the process is basically:

  • Find the WP plugin folder on your server. Create a new folder for your plugin.
  • Create a new document called plugin_name.php
  • Type in some properties about the plugin you are about to create, such as file name and author.
  • Go to the plugins on your WP dashboard. Your plugin should already be there! Activate it.

And that’s about it. All you have to do then is create your actual plugin functionality.

Writing the plugin

To get the functionality I was after, I used a combination of this WordPress help file and also having a peek at the Pocket WP PHP file. Eventually, this was what my own plugin PHP file looked like:

<?php
/**
* Plugin Name: JR links
* Plugin URI: http://james-ramsden.com/downloads
* Description: Use shortcode [JR_Links address="" name="" description=""] within table tags. This adds a row for a table of links.
* Version: 1.0
* Author: James Ramsden
* Author URI: http://james-ramsden.com
**/

function JR_links_funct( $atts, $content = null ) 
{
	extract(shortcode_atts(array('address' => '','name' => '','description' => ''), $atts )); //extract parameters

	$html = '<tr>';
	$html .= '<td width="111px"><a href=" ' . $address . '"><img src="https://eu2.searchpreview.de/preview?s=' . $address . '" /></a></td>'; //image
	$html .= '<td width="20%"><b><a href="' . $address . '">' . $name . '</a></b></td>';
	$html .= '<td>' . $description . '</td>';
	$html .= '</tr>';
	return $html;
}
add_shortcode( 'JR_Links', 'JR_links_funct' ); //the shortcode is called [JR_Links] and calls the function JR_links_funct
?>

The entire code inside the PHP file.

And that’s it! This is about as short as meaningful extensions get, and I’m pretty pleased as a first attempt.

The green text at the top is the plugin properties that WordPress reads to populate the plugins list on your dashboard. It’s best to just copy-paste this for your own plugins, as you’ll find it in every one.

The add_shortcut function is the bit of code that tells the WordPress editor to listen for a shortcode. When the shortcode [JR_Links] is used, then WP feeds back to this function, which in turn will call the JR_links_funct function.

Within the extract line, we have added the ability to listen for three arguments: address, name and description. We can then inherit these arguments as variables in our function. A variable called $html is then used to construt the HTML we want to output. When we’ve finished, we return $html, which then returns this text back to the WordPress page.

Using the new plugin

Now the dirty HTML work has been pushed into the background, creating the table is now much tidier. Creating the table is now as simple as:

<table>
<p>[JR_Links address="http://www.giuliopiacentino.com/" name="Giulio Piacentino" description="Architect, Grasshopper, RhinoScript"]</p>
...
</table>

If I want to make any changes to the layout, I can now do this within the PHP file. The shortcode is simply passing over the information required; it’s up to the PHP file on what HTML this is turned into. For maintainability, this is so much better. Since the same PHP file creates every line of the table, we only have to make a change once in the PHP file for the change to propagate through every row.

new-links-page

Add a new domain and WordPress installation through cPanel

If you have a website using webhost such as SiteGround, you are probably using the cPanel software to manage it. Many hosting packages allow multiple domains to be hosted. This short guide shows how to set up a second and a third domain on your hosting service through cPanel, and how to set up a WordPress installation on it.

I have such a package with SiteGround, and of course I am running james-ramsden.com on it. After a recent trip to Japan, I am wanting to create a new website called ski-hokkaido.com to document the trip (though we’ll see if that actually happens!), and to save costs I am going to run it from the same SiteGround hosting account. It’s been a while since I’ve done something like this, and it was a bit of a headache when I couldn’t remember how to do it, so hopefully this guide will jog both my memory if I need to do it again, as well as hopefully being useful for anyone else…?

This process is free of charge. It takes about 10 minutes of your time, though it will take between 2-48 hours for the servers to catch up and your new website to be live.

Step 0: What you need

  1. A new domain address that you want to set up
  2. A hosting account which uses cPanel as its management tool

In my case, I bought the domain from NameCheap, and I use SiteGround as my webhost.

Looking for a webhost? James-Ramsden.com is hosted by SiteGround, and I happily recommend it to others. If you are looking for a fast and good value web host, you can help support this site by signing up for SiteGround here.

Step 1: Point your domain to your webhost’s server

Your Domain Name Server (DNS) information is what turns human-readable website names (www.something.com) into a computer-readable address that helps your browser find which computer in the world it is supposed to be talking to. Your website is ‘saved’ physically on your webhost, so when a user types your web address into their browser, it needs to be able to find your webhost so that they can access your website.

Your domain is what allows this process to happen. The domain registrar essentially is the company that ‘points’ a browser towards the computer where a website is being hosted. When you have just bought a new domain, you have to make the link yourself between the domain and your website.

So how do we do this? Basically, have to find the DNS information for our webhost, and point our domain towards it.

Step 1a: Go to SiteGround (or your equivalent) and log in to cPanel. Under ‘My Accounts’, look for ‘Name Servers’ in the top left.

siteground

Keep this tab open.

Step 1b: We need to tell your domain registrar about the DNS addresses we found on our webhost, and the process may vary slightly depending on which company you use.

Open a new tab. Log in to Namecheap (or your own registrar) and go to ‘Domain List’.

namecheap1

Find your website and click the ‘Manage’ button.

namecheap2

Scroll down to the ‘Nameservers’ section.

Select ‘Custom DNS’ and copy the DNS information that you got from SiteGround into the textboxes.

namecheap3

Save changes.

Step 2: Set up your domain on your webhost’s server

We have now told your domain registrar to point to your webhost when someone enters your new domain into their browser, but we haven’t told the webhost what to do when they arrive. So now we need to set up our WordPress blog, and configure it so that it loads when someone comes to our webhost with this domain.

Firstly, you need to log in to your cPanel interface. I did this by going to SiteGround, logging in, going to ‘My Accounts’ and ‘Go to cPanel’.
dns6

Once inside, find ‘Addon Domains’.

dns7

Fill in the fields below.

dns8

The ‘New Domain Name’ is the domain you have just bought, exactly as you registered it, but without the http part. The next two fields should autofill to sensible values, or if not then replicate the patterns in the image. Finally, enter a password.

Step 3: Set up WordPress (optional)

The above step created a folder in our server space, but there’s nothing in it. You can of course do anything with this space, but here we’re going to install WordPress.

Many webhosts using cPanel make it easy to install WordPress through cPanel. Go back to your cPanel interface and find the WordPress installer.

dns9

Select ‘Install’. A form will appear where we set up our WordPress blog. Find your domain in the drop-down box.

wp1

Give the site a name and a description. (You can change these later on from the WordPress dashboard.) Leave ‘multi-site’ off unless you know exactly what it is, even if you have multiple WordPress blogs. The username and the password is how you log in to the WordPress admin view, where you design your site and create content. You don’t want people hacking this, as it gives them full control of your WordPress site, so give it a secure username and password!

If you have email set up on your webhost, you can use something like has is given to you. Alternatively, you can use any email address you like. This address isn’t visible from anywhere on your site by default.

wp2

Everything else can be left as default. Click ‘install’ at the bottom, give it a few minutes, and you’re done!

So… where’s my website??

You would think now, that if we enter our address of our new website in our browser, we should see a tantalisingly empty blog, waiting to be filled. You may notice that something does load when we enter the address, but it’s a generic page filled with ‘NameCheap… website coming soon!’ with words to that effect, and no way of actually doing… anything!.

The answer is simply, relax! Transferring over domain names tends to take a while, and sometimes as long as 48 hours. With NameCheap and SiteGround, in my experience it does take a couple of hours.

And when it’s ready, you can start to edit your WordPress website in the usual way – just head to http://mydomain.com/wp-admin. Once there, enter the login details you gave when you created the WordPress installation.

Have fun!