Customizing WordPress Using Custom Post Types

Introduction

One of WordPress’ greatest features is its ability for customization. There are many sites out there that could benefit greatly from these features. I’ve seen sites that sell cars and houses to simple music sites that could benefit from one specific customization function within WordPress, the register_post_type. The register_post_type function, as its name suggests allow the user (or theme) to add a new post type such as car, house or album. Once this post type has been registered, the user can then start adding functionality to WordPress that is unique to the post type. Using a custom post type opens up the use of custom taxonomies and more

Adding a custom post type

For this example I’m going to stick with the Car sales example. To add our post type we can define several labels that are used to populate menus and various options throughout the site. We also have to define some basic characteristics of our post type that we want WordPress to know about and handle for us. These include if we want to have an archive listing or if the post supports certain features such as excerpts.

register_post_type( 'car', array( 'labels' => array( 'name' => __( 'Cars' ), 'singular_name' => __( 'Car' ), 'add_new' => 'Add Car', 'add_new_item' => 'Add Car', 'edit' => 'Edit Cars', 'edit_item' => 'Edit Car', 'new-item' => 'New Car', 'view' => 'View Car', 'view_item' => 'View Car', 'search_items' => 'Search Cars', 'not_found' => 'No Cars Found', 'not_found_in_trash' => 'No Cars Found in Trash', 'parent' => 'Parent Car' ), 'description' => 'Car Post Type', 'public' => true, 'has_archive' => true, 'show_ui' => true, 'capability_type' => 'page', 'rewrite' => array( 'slug' => 'car', 'with_front' => false ), 'supports' => array('title', 'editor', 'thumbnail', 'author', 'page-attributes') ) );

A quick overview of a car tells us that there are certain characteristic that can be assigned to cars. Simple examples are:

Number of doors Body type, e.g. Saloon, hatchback, estate or 4×4 Color Fuel Type, e.g. Diesel or Petrol Engine size

These attributes or characteristics could the custom taxonomies we will be assigning to our custom post type. An example taxonomy would be the number of doors. It would look something like this:

register_taxonomy('car_doors', 'car',...
more →
avatar
@colaja tweeted: Customizing WordPress Using Custom Post Types http://t.co/uwZpb9L0xe via @DeveloperDrive

Creating a jQuery gallery for Flickr

Introduction

This week, we’ll be creating a simple jQuery gallery that uses the Flickr API to retrieve a list of images from a photo set and display them. We’ll also be using the API to get some additional information about the images and storing it using the HTML5 data-* attributes

The Flickr API

To use the API you need to register for an API key, it doesn’t take long and you can start here

There are 2 methods that we will be using for this tutorial, first we’ll need to get name and description of the specified photo set. To do that we use the flickr.photosets.getInfo method, it has just 2 parameters, the API key and the photo set id. The photo set I am using is from the National Library of Ireland and is title Working Life, you can see the photo set ID (72157626766436507) is easily read from the URL. This set is available under a Commons license. Next up we’ll need to get the list of images in the photo set, to do this we use the flickr.photosets.getPhotos method. This method takes a few extra parameters that allow you to control paging and what information comes back

jQuery

Just like our last jQuery plug-in, we’ll start off with the basic plug-in template and move on from there.

(function( $ ) { $.fn.flickr = function(options) { var url = 'http://api.flickr.com/services/rest/?jsoncallback=?'; var settings = $.extend( { 'api_key': 'API KEY GOES HERE', }, options); return this.each(function() { }); }; })( jQuery );

We’re going to make this plug-in completely self contained (except for CSS), so all the user has to provide is an empty div. To enable this, when the plug-in is initialized we will have to add any HTML elements we need.

var gallery = $(this); gallery.addClass('flickr-gallery'); gallery.append('<h2></h2><h3></h3><div class="viewport"></div><div class="browser"><ul></ul></div><div class="clear"></div>');

Here you can see I am adding some header elements as well as two divs. The “viewport” div is where we will have our main image, and the “browser” div is where we will have our list of thumbnails.

To populate the thumbnail list we’re going to use the jQuery getJSON function. To use the Flickr API all we need to do is specify the API key, the method we are using and the photo set id. We also set the format we want the response to be in.

$.getJSON(url, { method: 'flickr.photosets.getInfo', api_key: settings.api_key, photoset_id: settings.photoset_id, format: 'json' }).success(function(state) { gallery.children('h2').html(state.photoset.title._content); gallery.children('h3').html(state.photoset.description._content);...
more →
avatar
@ivana_ivanusec tweeted: Introduction This week, we’ll be creating a simple jQuery gallery that uses http://t.co/w5weFpoHOG

Creating a Google Maps shortcode for WordPress

Introduction

This week we’ll be extending WordPress by adding a custom shortcode. This shortcode will allow us to add a Google Map to a post using a simple piece of text in a post or page. Shortcodes are a quick and easy way to add functionality to a post in WordPress. They look something like this:

[ gallery ids="1,2,3,4"]

We’ll also using PHP based Object Orientated Programming (OOP) to create our shortcode. We’ll create a basic class, that has some static functions with in. We’ll be using static methods because we want some level of state to be kept.

Getting started

Our basic class will be pretty simple, it needs to register the shortcode and provide functions to render the shortcode and add the API JavaScript file.

class GoogleMap_Shortcode { static function init() { } static function render_shortcode($atts) { } static function enqueue_map_javascript() { } }

To create our shortcode we’ll need to first register it and then define it how it works and what HTML it creates. We’ll also need to figure out a way to add in the Google Maps API JavaScript. To add a shortcode to WordPress we use the add_shortcode function. This function takes 2 parameters, the name of the shortcode and the function to call when we want to render the shortcode. We’re going to call our shortcode “map” and our render function “render_shortcode”. Since we’re using a class, we’re going to take advantage of the PHP Magic Constant “__CLASS__”, this will maintain a reference to our class and ensure our function can be called.

add_shortcode('map', array(__CLASS__, 'render_shortcode'));

The add_shortcode needs to be called only once, so we’re going to call it from our “init” function, and then immediately after our class definition call it.

class GoogleMap_Shortcode { static function init() { wp_enqueue_script( 'jquery' ); add_shortcode('map', array(__CLASS__, 'render_shortcode')); } static function render_shortcode($atts) { } static function enqueue_map_javascript() { } } GoogleMap_Shortcode::init();

Now we have to start getting our shortcode to render. First up we need to define the attributes of the shortcode. One of these will be the Google Maps API key, you can sign up for one here, we’ll also want to be able to specify map related settings like the map type, zoom and naturally the co-ordinates we want to center on. We can define their default values using the shortcode_atts and extract functions.

extract( shortcode_atts( array( 'api_key' => false, 'id' => 'map-canvas-1', 'class' => '', 'zoom' => '18', 'coords' => '53.339381, -6.260405', 'type' => 'roadmap', 'width' => '480px', 'height' => '480px' ), $atts ) );

Here you can see I’m defaulting all the possible attributes, this means the user doesn’t have to specify them all in the shortcode if they don’t need to. The API key is needed for all instances of the shortcode, but we can cache the key from the 1st call so it does not need to be specified on all shortcodes on a page. If we declare a static variable inside the class and use it where ever we are in the class it will only need to be set once.

class GoogleMap_Shortcode { static $api_key = false;...
more →
Craig Francis says: Fair point, and for some that would be an advantage... but if you need to change the key, it would only mean changing it in 1...

Creating a simple to-do application – Part 4

Introduction

This week in part 4 of creating our simple to-do application we’ll be learning how to send email notifications/reminders. To do this we’ll be using the PHP mail method and learning how to schedule repeatable tasks on Linux using cron. The equivalent process for Windows is the task scheduler and it is pretty self explanatory. WordPress has what it calls the wp-cron alternative, but it’s use is limited as it requires someone to actually use the site.

Cron

Cron is the Unix/Linux schedule process, it allows users to configure tasks that are executed at defined intervals. It’s not exactly considered to be particularly user friendly, so many hosting providers have a simplified UI to help set it up. In any event, it is still beneficial to know the basics.

Cron jobs are specified in the ‘crontab’ file (typically in the /etc folder) Crontab is short for cron table, and as the name suggests it is a series of columns that determine when and what is run, split up in to tasks on each new line of the file. Each column has a specific time related function, with the last being the actual file that is executed. The column order is as follows:

Minutes (0 – 59) Hours (0 – 23) Day of month (1 – 31) Month (1 – 12) Day of week (0 – 6) File or command

You can specify any combination of the above columns, disabling columns is by way of the * character. This configuration method can lead to some confusing schedules being created. You can specify that any Monday, that is the 1st of the month at 11am execute some task. It would look something like this:

* 11 1 * 1 task.php

Overall it’s quiet a powerful system that you can configure to do almost anything. There are a few things to note, don’t schedule a task that takes 5 minutes to execute every minute. Cron will execute this and you will end up with duplicate scripts taking up resources and potentially causing issues.

PHP mail

PHP has a built in email function that is incredible easy to use. It uses the default SMTP server details in your php.ini configuration to send emails. Generally if you’re running in a hosted server this will be configured, if it’s not or if you want to use a different server you can use the ini_set function to update your configuration. The ini_set command would look something like this:

ini_set("SMTP", "smtpserver.yourdomain.com");

To actually send an email, you have to provide the following information:

The “to” address The subject The message Additional headers Additional parameters

The “to” address can be a simple one line “you@domain.com” or either a csv of email addresses. You can also specify the name of the person in this field as follows:

Bob Bobberson <bobby@bobberson.com>

Another quirk about the mail function is that the message body must be split on to multiple lines of no more than 70 characters. To indicate a new line you need to use the \r\n (CRLF) characters.

There is only one header that must be sent and that is the “from” header. You can also specify the “reply-to” or CC and BCC headers. The CC and BCC values have the same format as the “to” field. A full email would look something like this:

$from = "To Do Application <to-do@domain.com>"; $to = "Bob Bobberson <bobby@bobberson.com>"; $subject = "How to send an email in PHP"; $message = "Read this! Sending an email in PHP is really easy"; $headers = "From: To Do Application "; $headers .= "Bcc: Another attendee "; $headers .= 'Reply-To: ' . $from; $headers .= 'Return-Path: ' . $from; mail($to, $subject, $message, $headers);

I should also note, that if you are planning on sending lots of emails there are better alternatives out there that will queue emails and perform better in general. The mail function is not designed to scale quickly or well, however for once off emails it is sufficient

Building our script

So now we know how we’re going to schedule our emails and we also know how we’re going to send them, next up is what are we going to send? To do this it’s back to our MySQL database and a simple query. Here we’re going to do a simple select from our ‘tasks’ table where the ‘task_date’ is between 15 and 20 minutes from now. To do that we use the MySQL ADDDATE function.

SELECT `task_id`, `user_firstname`, `user_surname`, `user_email`, `task_name`, `task_priority`, `task_color`, `task_description`, `task_attendees`, `task_date` FROM `tasks` AS t INNER JOIN `users` AS u ON u.user_id = t.user_id WHERE `task_date` >= ADDDATE(NOW(), INTERVAL 15 MINUTE) AND `task_date`...
more →
Arjun says: Thanks for giving this list. I spent one hour time for this article, It is very useful info for me..

Creating a simple jQuery plugin for Pinterest

Introduction

Plugins play a great part in the success of jQuery. There are hundreds of them out there, and having the ability to create your own is a great skill to have. With all of the interest in Pinterest (no pun intended), I thought it would be a good idea to do up a quick and simple Pinterest sharing plugin for jQuery.

Getting started

First we need to grab the jQuery plugin boilerplate

(function( $ ) { $.fn.pinterest = function(options) { var settings = $.extend( { }, options); return this.each(function() { }); }; })( jQuery );

This boilerplate provides us with the ability to specify default configuration values (settings) and ensures that the infamous jQuery chaining ability is maintained (the return this.each). I’m going to take advantage of the default configuration values by specifying the default Pinterest image we’ll be using. This can be overridden when initializing the plugin by specifying the url to the preferred image.

Default image

Custom image

(function( $ ) { $.fn.pinterest = function(options) { var settings = $.extend( { 'button' : 'http://business.pinterest.com/assets/img/builder/builder_opt_1.png' }, options); return this.each(function() { }); }; })( jQuery ); $(document).on('ready', function(){ $('img#share').pinterest({ button: 'pinterest-alt.png'}); });

Now that we have a basic framework done, let’s start adding some functionality. We need to update the this.each function to initialize each image and add some events for us. I’ve chosen to have the icon hover over the image being shared. To do this, I need to wrap the image in a span element that positioned ‘relative’, I then need to append the share image and position it absolutely. I’m going with the bottom right, but feel free to have a play

(function( $ ) { $.fn.pinterest = function(options) { var settings = $.extend( { 'button' : 'http://business.pinterest.com/assets/img/builder/builder_opt_1.png' }, options); return this.each(function() { img = $(this); img.wrap('<span class="pin-it" style="position: relative;" />'); img.parent('span.pin-it').append('<img...
more →
Sean Meyer says: That's pretty cool. I've only ever done one jQuery plugin myself and that was just something simple to see if I could do it. I...

Creating a simple to-do application – Part 3

Introduction

So far we’ve created some basic PHP pages and added some simple authentication. Today we’re going to going to build on that by adding database support. This will allow us to add proper authentication to our application and start saving tasks. I should also note that I am currently writing PHP in-line and not using functions (or object orientated PHP) I will tidy this up in the next tutorial and spend more time explaining it and what it’s benefits are.

Last week

Last week we installed XAMPP, so you should already have MySQL installed and ready to go. If not, please check back on the previous tutorial here. If you decided to use IIS last week, you can download MySQL using the Microsoft Web Platform Installer, you can either install phpMyAdmin or download the MySQL Workbench tool

If you have any trouble installing or configuring any of the above, please leave a comment below and I will try and help you get sorted.

Creating our schema

Assuming you’ve got MySQL and phpMyAdmin installed, we can start creating our schema. So far we know that we will need at least two tables. Our user table for logging in and our tasks table. We also know that a user owns a specific task, so that tells us we’ll also need to use a Foreign Key to define the relationship.

First we will need a database to create our tables. A basic script to get us going would look something like this. It creates the database ‘todo’ and creates a ‘users’ and a ‘tasks’ table. It also defines the foreign key in the ‘tasks’ table for the ‘user_id’ column.

CREATE DATABASE todo; USE todo; CREATE TABLE IF NOT EXISTS `users` ( `user_id` bigint(20) unsigned NOT NULL auto_increment, `user_login` varchar(100) NOT NULL, `user_password` varchar(64) NOT NULL, `user_firstname` varchar(50) NOT NULL, `user_surname` varchar(50) NOT NULL, `user_email` varchar(100) NOT NULL, `user_registered` datetime NOT NULL default '0000-00-00 00:00:00', PRIMARY KEY (`user_id`), KEY `idx_user_login_key` (`user_login`) ) DEFAULT CHARSET=utf8 AUTO_INCREMENT=1; CREATE TABLE IF NOT EXISTS `tasks` ( `task_id` bigint(20) unsigned NOT NULL auto_increment, `user_id` bigint(20) NOT NULL REFERENCES `users`(`user_id`), `task_name` varchar(60) NOT NULL, `task_priority` tinyint(2) NOT NULL default '2', `task_color` varchar(7) NOT NULL default '#ffffff', `task_description` varchar(150)...
more →

Adding a simple authentication using PHP require and includes

Introduction

Please note that this tutorial has now been superseded by a later, more in-depth tutorial available here

Continuing on with our to-do application, in this weeks snippet we’re going to be using PHP’s require_once function. The require_once function is similar to the require function, in that it will execute and include any php code with the calling file but with one vital difference. It will only execute once. This is important for us in this tutorial as we are going to use it to validate our user.

There are a few things to note first, since this is a short tutorial I will be doing something that is not a good idea in a production application. I will be storing the logged in state in the $_SESSION variable, this is only temporary as next week we will be updating it to store it in a MySQL database. We will also be storing in the database additional information such as the source IP address and a timestamp to mitigate against session hi-jacking.

Getting started

First we will need to convert our existing index.html file to a php file. To do this, simply change the extension to ‘.php’ and open the file in your text editor. We will now also create a new php file called ‘authenticate.php’ and save it in the same folder as our new index.php.

Now inside our index file, we are going to add the following php code to the very top of the file.

<?php require_once('authenticate.php'); ?>

This means that as soon as the file is executed, it will read and execute our authenticate.php file. The contents of the authenticate file is also pretty straight forward for now. We’re going to ensure our session has been started (session_start), and then check to see if the $_SESSION variable contains our authenticated flag. If it doesn’t exist or is not set to ‘true’ we will re-direct the user to our 3rd new page login.php. To perform the re-direct we are going to update the header Location value to point to our login.php file.

By also adding the above code to our submit.php, we can also ensure that only authenticated users can add tasks.

<?php session_start(); if(empty($_SESSION["authenticated"]) || $_SESSION["authenticated"] != 'true') { header('Location: login.php'); } ?>

In the scenario where we have already logged in, the index.php file will continue to execute as normal and we shall see our form and table as usual.

Logging in

Next up, we are going to create our login page. For now, it will be just a simple username and password form that uses POST to send the provided details to itself.

<!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>Creating a simple to-do application - Part 1</title> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <div id="page"> <!-- [banner] --> <header id="banner"> <hgroup> <h1>Login</h1> </hgroup> </header> <!-- [content] --> <section id="content"> <form id="login" method="post"> <label for="username">Username:</label>...
more →
Ccornutt says: By the way, for anyone reading this article that didn't get it - please, please *please* do not hard-code passwords into your...