WordPress is a fantastic Content Management System (CMS) that is open source and free to use for your own website. While it is quite easy to get started and create content, especially with visual tools to style your pages. Sometimes you may have to design something that requires a little custom development. Today we quietly launched a new website for Simmo’s Offroad Tours. One of the main reasons why we made the new website is so the client can easily update content. Notably, show a list of upcoming tours that users can ‘Tag Along” to. We used a tool called Simple Table Manager to allow an administrator to log in and add a row to the database, in this case a tour, but we needed that information to auto-magically display on the website. For this reason, we decided to create a custom plugin.
Creating your first WordPress plugin is quite fun, and relatively simple if you have relative knowledge of PHP, the scripting language used by WordPress. The reason why we wanted to create a custom plugin was so we could present the information exactly how we wanted, while being efficient with our code and not relying on an existing plugin that have quite a large footprint as far as the server is concerned.
I’ll include my code below, and then I’ll explain it.
Hopefully that looks relatively simple. The first few lines are PHP comments that inform WordPress on the plugin’s name, version, author etc. I used a tutorial from Lynda to get this far.
From line 13 is where the magic really starts to happen, so as you can see this is a pretty simple little plugin. First of all, we create a function called “list_all_tours”. We then use a class called $wpdb to, as the WordPress Codex describes, “contain a set of functions used to interact with a database”. Essentially the Global command is allowing the plugin to go hunting outside of the general WordPress tables to retrieve information. Line 15 tells the server to retrieve information from the SQL table upcoming_tours, and then order the rows by date.
After this point, it’s time to start printing to the page. Line 16 prints a div into the page, and from then on it’s nesting all of the data we want inside of some divs and span tags, by concatenating strings.
The final piece of the puzzle is creating a ShortCode in Line 24, which is the delivery method of the plugin. Whenever [upcoming-tours] is typed into the page, WordPress will run the function ‘list_all_tours” from Line 13 into the space where the shortcode was typed.
Seems pretty simple right? A little bit of CSS and we are done. While it took me a few versions, it doesn’t take long for you to be able to create something fuctional. From these humble beginnings we can start building bigger and better things!