WPMU DEV's Blog - Everything WordPress » WordPress Tutorials - WPMU.org http://premium.wpmudev.org/blog The WPMU DEV WordPress blog provides tutorials, tips, resources and reviews to help out any WP user Mon, 26 Jan 2015 13:00:56 +0000 en-US hourly 1 http://wordpress.org/?v=4.0.1 How to Add Post Filters to Your WordPress Site http://premium.wpmudev.org/blog/add-post-filters/ http://premium.wpmudev.org/blog/add-post-filters/#comments Sun, 25 Jan 2015 13:00:07 +0000 http://premium.wpmudev.org/blog/?p=136622 A frequent request I come across is the ability to let users filter, or sort, posts on the front-end of their website.

Perhaps users want to view posts alphabetically, or maybe see only those posts with thumbnails? This already makes sense for regular posts but can be even more meaningful in the case of products, photos or other content types.

In today’s Weekend WordPress Project I’ll give you a quick rundown of how you can implement a feature like this in the Twenty Fifteen theme. Let’s get cracking!

Creating A Child Theme

As always, you need a child theme. We have a guide to child themes right here on WPMU DEV, I recommend giving that a read if you are not familiar with child themes.

Creating Controls

Let’s add three controls: one for ordering the posts, one for setting the direction of sorting and one for showing only posts with thumbnails.

The first step is to copy the parent theme’s index.php into our child theme.

Open the index.php file in your child theme and paste the following HTML below the main container (which should be on line 20):

And here’s what it looks like on the front-end:

Not so pretty yet but our form is in the right place

As you can see we are lacking a bit of styling. Let’s resolve that by adding some styles to the stylesheet:

Styled Filter
More work could be done but it looks much nicer

A reaction I frequently hear from newcomers to programming is: “how did he know that these are the styles that will make it blend into the theme?”

The solution is pretty simple: I cheat. I use the developer tools in Chrome to inspect the regular article elements. In this case, it let me see how the elements get their box shadow and their margins and I simply applied these rules to my own element.

Modifying the Query

Let’s select “order by title,” “ascending” and “posts with thumbnails” and submit the form. You should actually see a change without doing anything to the code.

To see why, let’s inspect the URL. It should be something like this:


The tidbits of information can be recalled in our PHP scripts using the $_GET variable. WordPress already knows what the order and orderby parameters mean and it uses them in the default query. As a result, if we only need ordering and order direction we’re actually all done.

That’s all great, but again, how did I know this? I could have used “order_by” as a parameter instead of “orderby.” In this case WordPress does not pick up on our intentions. I had a look at the WP_Query documentation in the WordPress Codex where there are a bunch of parameters, many of which can be used in URLs.

Now, let’s implement our post thumbnail parameter. A post has a thumbnail if it has metadata with the key _thumbnail_id associated with it. We’ll need to modify our query to make sure this is taken into account. Let’s do this now with query_posts().

Paste the following code above the get_header() function at the top of the file:

We merge the parameters of the original query with our own new parameter, which results in a different set of posts. Our form now works but it doesn’t remember our selections. Let’s fix that by rewriting our form and using some PHP.

Smarter Forms

In addition to listing all the options of the order by selector we need a way to indicate which one is selected. If we were to do this without a loop it would look something like this:

Do you understand any of that? I don’t blame you! Within each options we’re checking if the currently selected value is equal to the value of the option. If it is, we output the selected property. Let’s make this a lot cleaner with a loop:

This is a bit longer but only because we have three options. This is a way better format for managing any kind of selection. Let’s extend this to the whole form:

All done. The form should now remember our selections based on the $_GET variables in the URL.

WordPress Behavior

Remember how I mentioned that I know to use “order” and “orderby” because I looked at the WP_Query documentation? This is good practice, but it may lead to unexpected results. Find the slug of a category you have, say this category is “wordpress.”

Now use the following URL: http://yourwebsite.com/?category_name=wordpress. You should see your category archive, listing all your WordPress posts. This is just fine, but we have two problems:

If you have pretty permalinks turned on (which you should), the page has been redirected to a new URL, most probably http://yourwebsite.com/category/wordpress. Our filters will not be visible because the archive.php file handles this view, not index.php. In addition, our category name is not passed as a URL parameter so we will need to use some additional trickery to make our filters work.

The shortcut way of making this work is to deliberately not use the same parameters WordPress uses. You could pass the category name using the catname parameter in the URL since WordPress will not pick up on this. You can then feed this to the query using the correct parameter name. Something like this:

The alternative would be to use a function instead of outputting our form in index.php as is. You would need to detect the category from the WordPress query itself and display the current selection based on that.


Adding your own filters is not all that difficult but requires a bit of fiddling. In our case you may want to make sure the pagination is removed when the order is set to random. It could be replaced by a “show more randomness” button, which simply reloads the page.

Hopefully this article has given you the basics of how you can accomplish this for yourself and you will be able to build the filters you need.

If you have any questions about this project, feel free to ask in the comments.

http://premium.wpmudev.org/blog/add-post-filters/feed/ 2
How to Let Users Login to WordPress Using an Email Address http://premium.wpmudev.org/blog/email-login/ http://premium.wpmudev.org/blog/email-login/#comments Sat, 24 Jan 2015 13:00:00 +0000 http://premium.wpmudev.org/blog/?p=136605 It’s not unusual for users to forget the username they chose when signing up for a WordPress site.

Or, when registering for a site, a user might discover the username they want is already taken.

Fortunately, you can give users the option to login to your site with their email address, which they are less likely to forget.

In today’s Weekend WordPress Project, I’ll show you a couple of methods – a code snippet and a plugin – to help you easily add email login to your site.

Adding Email Login with Code

The first thing we need to do is remove the default authentication rights. Add the following snippet to your functions.php file:

Next, we’re going to add our own authentication. To do so, we’re going to use add_filter.

Add the following code to your functions.php files:

Here’s how it works:

The code checks if the username (now email) or password fields are empty. If neither are empty, it uses get_user_by to look for the user’s email. After finding a valid user, it then checks if the password is correct using the wp_check_password() function.

Thanks to Nishant Kumar at The Binary for this snippet.

Adding Email Login with Plugins

WP Login Email
The WP Login Email even updates the text on the login page of your site.

If you would rather not mess around with code, the WP Email Login plugin offers a tidy solution.

Simply install the plugin and it will work off the bat. It doesn’t include any settings, it just works.

WP Email Login is available for free in the WordPress Plugin Repository and is compatible with WordPress 4.1.

It also works great (after testing) with Multisite and BuddyPress.

Do users on your site forget their passwords? What other kinds of Weekend WordPress Projects would you like us to feature? Let us know in the comments below.

http://premium.wpmudev.org/blog/email-login/feed/ 0
Keeping Plugins Clean: Using Activate, Deactivate and Uninstall Hooks http://premium.wpmudev.org/blog/activate-deactivate-uninstall-hooks/ http://premium.wpmudev.org/blog/activate-deactivate-uninstall-hooks/#comments Fri, 23 Jan 2015 13:00:58 +0000 http://premium.wpmudev.org/blog/?p=136438 Plugin authors pour so much of their time and energy into the main functionality of their products that it’s understandable less important stuff falls by the wayside.

Take activation and deactivation, for example. While activation hooks are widespread – many plugins need to add some options, flush rewrite rules, maybe create a database table or check for version differences when they are installed – deactivation and uninstallation hooks are far less less common.

My point is that many plugin authors don’t take the time to clean up after themselves. Does the WordPress installation really need the custom table you created after the plugin is removed? Why not clear out a few options exclusive to the plugin before it is trashed?

In this article I’ll show you how to use activation, deactivation and uninstallation hooks to more easily initialize your plugin, and so you can clean up after the user is done with your product. If you skim through the article, I strongly suggest taking a peek at the “Additional Security” section at the end, which complements the code with a few checks for security.

The Activation Hook

The activation hook is pretty straightforward but since installing things is a bit of a special case we’ll need to pay attention to the sequence of events. Before we go into all that, here’s the simple example:

The key to it all is the register_activation_hook() function. The first parameter is the path to the main plugin file, the second parameter defines the function to run. Internally, the register_activation_hook() function is a wrapper for the “activate_[plugin_name]” action, but since it’s a bit easier to use it’s unusual to see the hook in plugins.

The Installation Sequence

It’s important to understand the installation sequence because it does prevent the use of some methods you may be used to. register_activation_hook() is called in-between the user clicking on the activation link and consequently seeing the activation notice. It runs on an intermediary page, which redirects immediately, before any hooks could have a chance of running. Let’s look at an example to see why this is a huge bummer:

Flushing Rewrite Rules

A number of plugins create custom post types. It’s a smart move to flush the rewrite rules on activation to make sure users don’t get a 404 error when visiting a post from the new custom post type. The following code seems logical but will fail.

It seems perfectly fine: The custom post type is created and on activation we flush the rewrite rules. The only problem is that the custom post types are not yet created when the rewrite rules are flushed. Here’s how the process flow looks:

  1. User installs the plugin
  2. User clicks activation link
  3. An intermediary page is used to run only the activation hook, nothing else. As a result, the rewrite rules are flushed.
  4. The plugin is active and code runs as usual, the custom post type is registered

A solution was posted on Stack Overflow, which is officially endorsed by the WordPress Codex, which solves our little problem. The solution involves adding an option, which indicates the plugin was just installed.

If this option exists we do our activation stuff and delete it. Something like this:

I personally don’t like this solution too much. The problem is that the check on line eight runs on every single page load. There’s nothing to be afraid of, it won’t put a big load on your servers, it won’t slow down the website for your users. It’s a very quick check which has negligible performance impact, however it is unnecessary 99.9% of the time.

This is why there actually is a better solution, mentioned in the Codex in the documentation for the flush_rewrite_rules() function. In this solution we use the modularity of our functions to register the custom post type on activation separately:

Instead of relying on a check, which needs to run all the time, we use the activation function to register our post types. Note that once our plugin is activated the post types will always be registered from the init hook.

This is a sad example of the Codex being all over the place. Generally, WordPress does have good documentation, but if something seems wasteful or illogical, don’t be afraid to do some research of your own.

Creating Database Tables

Another task some plugins perform is creating database tables. Take care as this is unnecessary more often than not, but there are some legit use cases. Here’s an example from the Creating Tables Codex article, which also shows us how multiple activation calls can be used:

The first function, jal_install() creates a new database table. The second function, jal_install_data adds initial data to the table. Instead of using register_activation_hook() to add one function, which contains all this code, we can use register_activation_hook multiple times.

This is great practice for modularity. On one hand you don’t have to add initial test data – it’s as simple as removing the activation hook – so you can keep the function in tact. On the other hand, you are free to re-use these functions anywhere since they are well-separated.

Dependency Checks

Another common task for the activation function is checking for dependencies. Your plugin may rely on a specific version of WordPress, another plugin or even a specific version of PHP. The following code checks for a minimum WP and PHP version and redirects the user (without activating the plugin) if necessary:

The Deactivation Hook

Deactivation hooks run when a user has deactivated a plugin, but before it is uninstalled (deleted). Their use is identical to activation hooks:

Deactivation only means that the user has deactivated your plugin so you won’t want to do as much as during an uninstall. You may want to flush rewrite rules perhaps but at this stage you won’t want to get rid of all your options and your database table if you have one.

This is pretty straightforward but I will pay special attention to flushing rewrite rules as these are problematic once again. The codex recommends doing them the following way, but this does not work:

The reason this doesn’t work has to do with the same type of reasoning as we had before. When deactivation runs the init hook has already been performed, which means that as we are deactivating our custom post type is registered. The rules are indeed flushed but they take into account the custom post type.

A Trac ticket is in place to tackle this but until then I actually can’t give you a very good way of doing this. The only way I’ve found that works is to delete the rewrite rules altogether:

While this has worked for me in the past I would not recommend this either. The uncertainty this introduces is greater than the problem of having a few extra rewrite rules. I would rather display a note to users asking them to visit the permalink settings after deactivation which would flush the rewrite rules. Until a solution is implemented we’re stuck with this, sorry!

The Uninstallation Hook

There are two ways to run code when a plugin is uninstalled. You can use the uninstallation hook via register_uninstall_hook() or you can use a dedicated uninstall.php file within your plugin. While I will show you both, the preferred method is using the uninstall file.

The main issue with the uninstallation hooks is that “It prevents the main plugin file from being run during uninstall, which can be problematic if the plugin runs code in the global space. It’s also better in that the uninstall code is centralized.”Scott Riley

The code below shows the uninstallation process using a basic hook:

As discussed, this is not the best solution. A far better way of handling uninstallations is the uninstall.php file. All you need to do is create it, it will be used if it is available.

As you can see, this is actually a simpler solution and best of all, it is self-contained.

Additional Security

I didn’t want to over-complicate the examples so far with security, but you really should take some steps to ensure that only those allowed to do so can run these actions. The following snippet should be used on activation and deactivation:

This code block makes sure that the user has the permissions to perform this action and that the action originated on the proper page. This should protect against most malicious attempts.

The uninstallation process is special so we’ll need to use slightly different code:


If your plugin adds stuff to WordPress it’s your duty as a developer to remove it when the user decides to delete your plugin.

Using the activation, deactivation and uninstallation methods outlined here you can build a system which does this safely and securely.

I highly recommend reading this Stackexchange thread, which outlines these processes in OOP environments as well.

Do you find that plugins leave your database in a mess when you remove them? Let us know what you think in the comments below.

http://premium.wpmudev.org/blog/activate-deactivate-uninstall-hooks/feed/ 2
Loading WordPress Posts Dynamically With AJAX http://premium.wpmudev.org/blog/load-posts-ajax/ http://premium.wpmudev.org/blog/load-posts-ajax/#comments Wed, 21 Jan 2015 13:00:00 +0000 http://premium.wpmudev.org/blog/?p=136223 AJAX has become all the rage in the past couple of years and for good reason. AJAX (Asynchronous JavaScript and XML) is a way to have a “conversation” with the server and display the results without reloading the page.

This technique allows us to refresh “Like” counters, add items to a shopping cart, create dynamic forms and much more – all without reloading the page.

In this post I’ll show you how to load posts in place with AJAX using the Twenty Fifteen default theme as our base.

We’ll look at why AJAX is used and, starting with a simple example, building AJAX loading functionality into Twenty Fifteen.

Why Use AJAX?

When WordPress loads the first page of posts on a WordPress site, it requests them from the database and uses a loop to display them using the markup we’ve added. Aside from this, navigation menus, widgets, graphics and other media, javascript files, stylesheets and a bunch of other things are loaded.

Network requests.
Note that 72 requests are made on each page load.

As you can see in the image above (taken from Chrome Developer Tools), a fair number of assets are loaded. There is room for optimization here and some assets like scripts will be cached, but even then it is a lot.

When page two of our posts is loaded it all happens again. WordPress retrieves the posts and displays them using our markup. It also loads all the outlying elements of the page all over again. In many cases (but not all) this is a waste of bandwidth and detrimental to user experience. After all, no one likes waiting around for pages to load.

Getting Started: Creating a Child Theme

Before we modify Twenty Fifteen we should create a child theme. This ensures we can continue updating the theme without losing our changes. You can read all about how to do in in out guide How to Create a WordPress Child Theme.

Hello AJAX!

Let’s begin with a simple example that demonstrates how AJAX Works. We’ll target the links inside the pagination strip at the bottom of the page so that when you click on a page number it will dynamically load that page using AJAX. When a pagination link is clicked we will send a request to the server and alert the result.

We’ll be targeting the number links inside the pagination section.

Enqueuing Our Javascript

Our first port of call is creating the JavaScript file and enqueueing it via our theme’s functions.php file.

I created a js folder and a ajax-pagination.js file in it. Once you have done the same, open your functions file and add the script to the already existing theme_enqueue_assets() function:

If you’re confused about enqueuing read our article on adding scripts and styles to WordPress the right way. In a nutshell, we’ve told WordPress what we’d like to call our script (parameter one), where it is located (parameter two), what the pre-requisites are (parameter three), the version number (parameter four) and that we’d like to load it in the footer (parameter five).

Note that when enqueueing the stylesheet I used get_template_directory_uri(). This function always points to the directory of the parent theme. When enqueueing our script I used get_stylesheet_directory_uri(). This points to the child theme’s directory if used within a child theme.

Since we’re loading the script in the footer you can paste alert( 'Script Is Enqueued' ) into ajax-pagination.js and reload the page to check if it works. If it does, the text should be alerted properly.

Creating an Event

The next task is to create an event which will trigger an AJAX call. In our case the event is the clicking of a specific link. To target the link we’ll need to find out a bit about the element classes and IDs around it.

Pagination Source
The source code for the pagination from Chrome Dev Tools.

In case you’re wondering how I got this to show up, I pressed Shift + Command + C on my Mac (Shift + Control + C on Windows), hovered over the element I wanted to inspect and clicked it.

This tells me that our pagination links have the class page-numbers, the next link also has the class of next and these are all contained in a nav element with the class of nav-links. Not shown here is the previous link, which has the class of prev in addition to the regular page-numbers class.

For the time being, let’s not worry about all that, let’s just target any link within the pagination container. We can create a simple alert like this:

Note that everything is wrapped in an anonymous function. I recommend you do the same. Take a look at this thread on why this is helpful. I’ve created a click event, prevented the default functionality from firing (i.e. loading the page) and I’ve alerted some text.

Creating an AJAX Call

Instead of working with client side data (alerting a preset text) we should grab some dynamic data from the server side. We’ll need to do a tiny amount of prepwork. Here’s why: We need to give the AJAX call a URL to work with. Our Javascript file has no knowledge of our environment, so we can’t use something like get_stylesheet_directory_uri() in there. We can, however, use a localization technique to pass variables to our JavaScript. Let’s do that now in our functions file:

By adding this code inside the my_enqueue_assets() function we will have defined the ajaxpagination object (parameter 2). The object will receive its members according to the array supplied as the third parameter in the wp_localize_script() function. In other words, once we’ve added this code we should be able to use ajaxpagination.ajaxurl to define the URL to the admin-ajax.php which we use to handle AJAX calls.

The reason this works is that the localization function outputs the definition of this object before our JavaScript is loaded. It looks something like this:

Getting back to our JavaScript file, we now have everything we need to build an AJAX call. Here’s how:

As you can see the $.ajax() function is what we’re using here. There are special functions for post and get methods but I prefer using this function because of its flexibility. You can read about all the parameters in the jQuery Documentation.

Using the url parameter we pass the URL of the script we want to send data to. This should be the admin-ajax.php file which can be found in the wp-admin directory. We defined this above via the wp_localize_script() function.

The type is set to post. We could also use get, our query is not too sensitive but I prefer to post data unless the user needs access to the parameters.

The data parameter is an object which contains the data you want to pass. In our case I will be able to access a $_POST['action'] variable, the value of which would be ajax_pagination. You can pass as many as your application requires of course.

AJAX Call Alert
0 is returned if no server-side code is written.

Finally, the success parameter is a function which alerts the result of our AJAX call. We’ll make this a bit fancier below, for now this is sufficient for testing. If you try clicking on a link now it actually works but won’t be very useful since we haven’t defined the server side code. In fact, what you should see alerted is 0.

So why does this happen? When I said “we haven’t defined server side code,” I wasn’t entirely truthful. We haven’t, but WordPress has. There is some content in the admin-ajax.php file we are using. If you take a look at the source code of that file you should see that the script uses die( '0' ) in a couple of cases.

If we don’t supply an action the admin-ajax.php script dies and returns 0. If we do supply an action but we don’t hook into the required WordPress hooks nothing happens and at the very end of the file we die again, returning 0. In conclusion we are already communicating with the server.

Communicating With WordPress

To get a meaningful answer from WordPress we need to define some WordPress actions. This is done using a set pattern. Let’s dive in by continuing our example in the functions file of our theme:

I’ve hooked a function to two hooks. Hooks that take on the wp_ajax_[action_name] format are only executed for logged in users. Hooks that take on the wp_ajax_norpiv_[action_name] format are only executed for non-logged in users. The great benefit of this is that you can very easily separate functionality.

The action names I mentioned above refer to the action defined in our AJAX call in Javascript (action: 'ajax_pagination') – they must match. The function name can be anything you like, I used my_ajax_pagination for clarity.

The function itself can contain anything you’d like. You can log out users, grab their data, publish a post and so on. Whatever you want to return to Javascript you must echo. In the example above I’ve echoed the title of the blog, pulled in dynamically via the get_bloginfo() function.

The final step is to use die(). If we don’t define this, the die function defined in admin-ajax.php at the very end of the file will kick in and you will end up echoing 0 in addition to whatever else you are echoing. If you try out the code above you should now see the title of your website returned.


That concludes our basic example! Before we move on to pulling in posts via AJAX, let’s quickly recap the steps necessary to perform an AJAX action:

  • Enqueue a Javascript file if you don’t already have one
  • Use wp_localize_script() to pass the URL of your admin-ajax.php file
  • Create the AJAX call in Javascript
  • Hook a function using the appropriate hook name
  • Code the function which may return data back to Javascript

Loading Posts With AJAX

Now for the juicy stuff! I started this project by writing the JavaScript code for it. Without further ado, here is the basic version. We’ll expand on it with some tweaked user experience soon.

This is much the same as our basic example. The first thing you’ll notice is that I’ve added a way to detect which page the user wants to request. Each link has a span element in it which is hidden (it is there for screen readers). I make a clone of the element to make sure I don’t modify the original, remove the span and parse the remainder as an integer. This gives us the page number we need.

I will also need to know the query parameters used. On the main page this is pretty simple, it’s just the paged parameter since we’re working with the default query. If we start off on an archive page (like a category archive) we’ll need to know the category name as well.

We’ll pass the query variables using the localization method we learned earlier. For now we’ll use ajaxpagination.query_vars even though this is not yet defined. Finally, on success we remove all article elements from the main container, we remove the pagination element and append the return value of our AJAX call to the main container.

This return value will contain the posts and the new navigation element. Note that I’ve changed the name of the parameter from response to html because it makes a bit more sense. To finish up we use the localization array to pass the original query parameters.

The following function should be placed in our my_enqueue_assets() function replacing the localization we had earlier:

All we need to do now is flesh out the my_ajax_pagination() function. Whatever this function echoes will replace the content on our page. Here’s the final code with an explanation below:

Using our passed parameters we build a custom query. This involves basically taking the query variables we passed and making sure that the page number we passed overwrites the paged parameter. We then use our final $query_vars array to create a new query.

We need to make the $GLOBALS['wp_query'] variable equal to our new posts object. The reason we need to do this is that the the_posts_pagination() function uses this global variable.

Next, notice that I’ve added a function to the editor_max_image_size filter and a few rows down I remove it. This was something unexpected that came up. I actually created a WordPress Trac Ticket. We may see some progress on it! Here’s the issue:

When images are loaded in the post they all look just fine. However, if you complete this tutorial without these filters your images will be narrower, only 660px wide instead of the necessary 825px. The reason for this is that the function that loads the images eventually calls a function named image_constrain_size_for_editor(). This function makes sure that images in the post editor aren’t too wide. To determine weather this size reduction should take place it uses the is_admin() function. Since our code runs through admin-ajax.php which technically is in the admin, WordPress scales our images down, mistakenly thinking we are using them in the editor.

Luckily we can use the editor_max_image_size filter to determine the maximum size for the editor. Since we want to leave everything as is, except for during our AJAX call we add the filter using our custom values (array( 825, 510 )) and then immediately remove it just to make sure it doesn’t cause trouble anywhere else.

The next step is to use our query to list our posts. I copied a lot from the index.php file in the parent theme. if there are no posts we use the template which is meant to handle that, otherwise we loop through the posts and use the post display template. Finally we use the same pagination format we see in the index file.

Better User Experience

With AJAX solutions like this, it is extremely important to focus on user experience. I’m working in a local environment so everything loads really quickly, but on a production server images and other assets may take more time to load.

Due to this you should at least add a loader or loading text and disable further clicks on the navigation elements. We will take care of these by making the posts and the navigation disappear right after the user clicks and displaying the text “loading new posts.” When the success event fires we remove the loading text and display the posts. Here’s our updated AJAX call:

We now have a separate beforeSend and success function. The former is performed as soon as you click the link, before the AJAX call is sent to the server. The later is performed once we receive data back from the server.

Before the call is sent we remove the articles and the navigation. This makes sure users can’t keep clicking on navigation links while they’re waiting for things to load. Next we scroll to the top of the document. Then, we append a loading notification to make it clear to users what’s going on. I’ve used the same markup as Twenty Fifteen uses on post-not-found pages. In the success function we remove the loader and load our content, all done!

AJAX Pitfalls

AJAX is extremely powerful; apart from loading posts you can perform all sorts of actions via AJAX calls. There are quite a number of dangers and things to look out for while using it, here are a few:

Safety can be a major concern. If you want to delete a post via AJAX you need to make sure the user has the intent and the permission (using nonces), for example. When using regular methods WordPress has built-in protections in some cases but with AJAX you usually have to think of this on your own.

Graceful degradation is another facet of AJAX, although something that is becoming less important. Basically: no JavaScript, no AJAX. If you rely on AJAX heavily, users who have it disabled will not be able to use our application. Javascript has become so ubiquitous that this is almost irrelevant, but may come up in some situations. In this case you need to make sure that clicking on the actual link will work as well.

User experience is very frequently overlooked. AJAX functionality is indeed cool, but a reliably working website is cooler. Users are used to pages loading when they click links. You need to make everything very transparent, users should know what is going on and why. You should use AJAX to enhance your work, not to bring as much bling as you can to the table.


As you can see, implementing AJAX requires a bit of preparation and practice but once it’s second nature you’ll find that it comes easily. It probably took you a while to read through this and it will take even more time to do it for the first time, but I coded the whole example in about 15 minutes.

AJAX is one of those techniques which can be difficult because it encompasses almost all programming languages used in a framework like WordPress. Things are spiced up further by having to adhere to conventions like hooks and localization.

Practice makes perfect. I guarantee you’ll fall in love AJAX if you start to use it.

Have you implemented AJAX on your site? What other uses are there for AJAX in WordPress? Let us know what you think in the comment below.

http://premium.wpmudev.org/blog/load-posts-ajax/feed/ 9
How to Customize Twenty Fifteen to Make it Your Own http://premium.wpmudev.org/blog/customize-twenty-fifteen/ http://premium.wpmudev.org/blog/customize-twenty-fifteen/#comments Tue, 20 Jan 2015 13:00:00 +0000 http://premium.wpmudev.org/blog/?p=136061 I recently praised the new Twenty Fifteen default WordPress theme for its clean look and focus on sharing beautiful content.

I like its vertical rhythm, the layout of the sidebar and the responsive behavior. It really is a beautiful theme.

But while I love how it looks, there’s always room to make it your own. Twenty Fifteen offers a few customization options but there is a lot more you may want to do to style it to your liking.

In this post I’ll take a look at a number of ways you can turn an already awesome theme into a site design that’s just right for you. We look at the built-in customization options, some plugins to add further style improvement, and self-coded solutions to some problems problems, albeit minor ones.

During the course of this article we are going to explore:

  1. Default Customizations
    • Colors
    • Background images for the main content and sidebar
    • Using the social menu
  2. Plugins
    • Adding support for Google Fonts
    • Adding a Twitter feed to the sidebar
    • Adding support for tiled galleries, sharing links and more
  3. Coded Solutions
    • Switching the sidebar to the right
    • Adding an image credit below posts
    • Removing the author section below posts
    • Modifying the color of content boxes

Default Theme Customizations

The main place to go is the Appearance > Customize section in the admin. This should bring up the Theme Customizer with the following options:

Customizing Twenty Fifteen
Available customization sections for Twenty Fifteen

Site Title and Tagline

This section of the customizer allows you to configure the title and subtitle of your website. This is standard functionality for almost any theme.

In addition, you may choose (via a checkbox) to disable this completely. This is pretty helpful if you want to add a header graphic with your logo via a child theme.

I’ve found that in this the the title and subtitle can be used pretty well for a quick bio as well. I prefer it over using a widget.

Two types of Intro
Difference between the title and subtitle and a widget.

The screenshot above shows the title and subtitle on the left and a regular text widget on the right. That’s as big as the heading gets in the widget, but disappointingly of all the widget cannot be placed above the menu – right at the top of the page, which is how I wanted it to be.


The colors section gives you access to the most visible customization options – changing your colors. There are four settings:

  • Base Color Scheme: Allows you to choose a color preset for your content and sidebar.
  • Background Color: Sets the background color for the main content area. The content boxes will retain their original colors.
  • Header and Sidebar Text Color: Sets the text color for the header and the sidebar. The sidebar becomes the header on smaller screens.
  • Header and Sidebar Background Color: Sets the background color for the sidebar/header area.
Color variations
Some color variations.

Header and Background Images

These two sections contain one setting each that governs the background image for the sidebar and the content area respectively. Even if you will be using an image here make sure to set a background color which looks good. If something goes wrong and your image doesn’t load your readers will still see something visually pleasing.

Background image
Background images set for the sidebar and content.

In case you’re wondering, there is no way to have a single background image span all the way across and have the sidebar black with some opacity. The screenshot above kind of looks like that but it’s actually two images.

Navigation, Widgets and Front Page

The navigation section allows you to assign your menus to the two menu locations available within the theme. There’s a regular page menu named “Primary Menu” and a social menu named “Social Links Menu” available. We’ll take a look at these in a bit more detail later, assigning them from within the Menus section.

If you haven’t tried the widgets managed in the customizer yet this is the perfect opportunity to do so. It was overhauled in WordPress 3.9 and is much more usable than before. You can create and preview widgets right from the customizer – a superb feature.

With the Static Front Page section you can select a previously created page to use as your front page. Use this if you would like to show something else than your latest posts on the front page.

Customizing Menus and Social Links

Menus in Twenty Fifteen
An example of a regular menu and a social link menu.

If you head on over to Appearance > Menus you can assemble menus for yourself. There is nothing new here. If you would like to learn how this works take a look at the WordPress Menu User Guide.

Twenty Fifteen does offer an added feature, the option to create a social icon menu with links to your favorite services:

When creating a social menu you should create a regular menu and link to a supported site. You don’t need to worry about what you name the menu item, the correct icon will be used based on the link provided.

The following is the full list of available social sites you can link to:

  • CodePen
  • Digg
  • Dribbble
  • Dropbox
  • Facebook
  • Flickr
  • GitHub
  • Google+
  • Instagram
  • LinkedIn
  • Path
  • Pinterest
  • Pocket
  • Polldaddy
  • Reddit
  • Skype
  • StumbleUpon
  • Tumblr
  • Twitter
  • Vimeo
  • WordPress
  • YouTube

Useful Plugins

If the default customizations aren’t enough to tailor Twenty Fifteen to your liking, here are a few plugins that offer additional styling options.

Adding Support for Google Fonts


Twenty Fifteen uses Noto Serif and Noto Sans, two great fonts available from Google Fonts.

Regretfully, there is no built-in way to customize the font family, however a plugin named Typecase solves all that. WP Tavern explains in detail how the process works.

Once you download and install Typecase you will be able to select a number of fonts you want to make available to the theme customizer. Next, visit the Theme Customizer and use the options to set the fonts to use for the body copy and headings.

Typecase also allows you to add custom selectors to tailor your fonts to specific elements. This is an extremely powerful way of adding fonts to themes without modifying the themes themselves.

Adding a Twitter Feed


Adding a Twitter feed to the sidebar is probably one of the best things you can do to get people interacting with you. I recently stumbled upon the rather lengthily named Easy Twitter Feed Widget Plugin, which is one of the best I’ve used so far.

Setup is as easy as pasting a widget ID, and it allows you to extensively customize the look of the feed.

Tiled Galleries, Sharing Links And More


With a download count nearing 14 million, Jetpack is one of the most popular plugins available. It is made by our friends at Automattic and includes a huge number of features which can be turned on or off selectively.

Tiled galleries are one such feature I like, creating a masonry style gallery from your gallery shortcodes automatically. The beauty of this is that you don’t need to do anything special when inserting your galleries, just turn the feature on.

Another often used module is the sharing section which can be added to the bottom of posts automatically. Here is how it looks in Twenty Fifteen:


Customizing Twenty Fifteen With Code

Before we get stuck into customizing the theme, we should create a child theme.

This is extremely easy, but if you’re not sure how to do it check out our handy guide to child themes. Child themes allow you to modify an existing theme without touching its code. This enables you to update the parent theme without losing your changes.

Once you have created your child theme you’re ready to start implementing some custom changes.

Moving The Sidebar To The Right

What’s the Problem?

There’s no option to switch the sidebar to the right side of the page if you prefer it that way.

How to Fix It?

To move the sidebar to the right you’ll need to add only a couple of styles to the style.css file in your child theme.

The Solution

Here’s the full code, explanation ensues:

So how do I know to do it like this? I simply used Chrome Developer Tools to figure out what the styles are. Hit Shift + Command + C to bring up the menu and hover over the sidebar (in OS X). The sidebar (.sidebar) has some rules which push it to the left by default. The main content area (.site-content) has rules which push it to the left.

I reversed these rules, taking care to overwrite them properly. Take care when doing this because some rules need to be set to their default. For example: when changing a float you can simply say float:right. Since this is defined as left originally the rule is overwritten. However, if a rule is set as margin-left:20px; you are not rewriting it by defining margin-right:20px in the child theme.

You are saying that the element should have a 20px right margin in addition to having a left margin. In these cases you should write: margin-left:auto; margin-right:20px;. This is pretty obvious when you’re writing out all the rules, but I sometimes make this mistake when overwriting rules and I spend a bit of time figuring out what’s wrong!

The last piece of the puzzle is to make sure the background separator lines up with our new layout. The separator is added using the ::before pseudo-selector. By making sure the position of this element is fixed to the right instead of the left we’ve completed our sidebar change.

Make sure to wrap the code in a media query. We only want to apply these styles to large screens. On smaller screens the sidebar should still become the header. By default this happens on small desktop screens, at 955px, or 59.6875em.

Adding An Image Credit Below Posts

What’s the Problem?

I like to say who is responsible if I use an image from around the web but there’s no option to add image credits in Twenty Fifteen.

How to Fix It?

Use Advanced Custom Fields and place the information in your template via a child theme. I’ll give you a rundown of how I did this on my website, but for more informal about this take a look at Creating A Workout Diary With WordPress to see how it works.

The Solution

In Advanced Custom Fields I created a WYSIWYG text field, which is shown on every post edit page. I could have made it a URL field but that would have limited me on the front end.

By using a text field I am free to write a sentence or two about the image if I like.

ACF image credit.
The image credit field I created in ACF.

At this point you can add image credits to all your posts but they won’t show up on the front-end. Open up your functions.php file and let’s use a hook to tack this info on after the post content:

This code takes the original content of the post and returns it after adding a our image credit string to it. Notice that I’ve used a specific HTML format:

My reason for doing so was that Jetpack uses the same structure to output some of its content, like the sharer section. I wanted it to mimic this so I used the same HTML. Before testing it out, head into your style.css to tweak the look a bit. Use the following to make it look just like it would if it were a Jetpack module:

Note that at the very end I modify the font size of all sections which use the .after-post-section .section-content selector. You may want to remove this if you’d like the text to be a bit bigger.

Image credit.
The image credit and the Jetcpack sharer

Removing the Author Section

What’s the Problem?

An author bio is displayed at the bottom of every post, which looks great, but if you have a single author website it’s completely unnecessary since your information will likely be displayed in the sidebar.

How to Fix It?

You can do this two ways: You can use the stylesheet to simply remove it from view, or you can remove the functionality altogether.

The Solution

To remove it from view go to your style.css file and add the following: .author-info { display:none; }. If you choose this method the text will still be there but it will be hidden from view.

If you would like to prevent content from loading when it isn’t needed you can remove it altogether, HTML and all. To do this you will need to copy and paste the content.php file from the parent theme into your child theme.

Open the file up and look for a section which starts with // Author Bio. Delete everything from the starting PHP tag to the ending PHP tag. Here is the full code which needs to be removed:

Changing Content Box Colors

What’s the Problem?

The Theme Customizer doesn’t allow you to change the color of content boxes.

How to Fix It?

You can change the color of the content boxes (and the text within them) to make some more interesting patterns. You will only need to modify styles so everything can be written in your child theme stylesheet.

Box color
A custom colored box in Twenty Fifteen.

The Solution

To achieve the effect seen in the screenshot above I had to change a few styles. Changing the background and the text color of the box is not enough because links and other elements may override them.

If you’d like to get the exact same design as above use #000000 for the content background and #303030 for the sidebar background in the theme customizer. Take care as some items within the post content may override these styles. You can already see an example in the screenshot – the pre tag. This looks OK in the design but other elements may override, with less pleasing results. If this is the case, simply add a new rule to your stylesheet to use your own colors.

Creating Borderless Boxes

What’s the Problem?

In some cases you may want to create borderless boxes, for a slider for example. Take a look at the screenshot below to understand the issue better.

A borderless and a regular post one under another.

How to Fix It?

We could set one of the post formats to be borderless, but I would prefer to leave them as is, the design is great. Besides, I may want to show images inside boxes with borders and borderless boxes as well.

The solution I came up with involves Advanced Custom Fields yet again. I created a true/false type control, which is output for each post’s edit screen. This allows me to set whether I want a particular post to be borderless or not.

The borderless control is just under the previously discussed image credit area.

The Solution

We’ll detect the state of this box whenever a post is loaded and output a special class if it is ticket. This can be done by hooking a function into the post_class hook:

We use the get_field function to see if the borderless box is ticked. If it is, we add it to the array of classes which will be added to the post. From here on out it’s largely subjective what you want to do. You can remove the border but keep the meta box, remove the meta box altogether, etc. I opted to remove everything:

By the way, if you would like to add a permanent slider to the top of your homepage, this is the perfect way to do it. All you need to do is add a slider as the post content and mark the post as sticky. In my demo I used the Meta Slider plugin to create the slider.


As you can see, there are numerous ways to customize Twenty Fifteen to make it just right for you. The built-in customization gives you control over some basic settings, while plugins can do a lot to extend what is already an awesome theme.

If you need more fundamental changes almost anything can be achieved via a child theme. You can remove elements, add your own and customize the style of everything in a modular way.

If you would like to see some other customizations of Twenty Fifteen or you have tweaked the theme yourself, let us know in the comments below.

http://premium.wpmudev.org/blog/customize-twenty-fifteen/feed/ 3
The 10 Most Popular Free and Responsive WordPress Themes Reviewed http://premium.wpmudev.org/blog/free-responsive-wordpress-themes-reviewed/ http://premium.wpmudev.org/blog/free-responsive-wordpress-themes-reviewed/#comments Mon, 19 Jan 2015 13:00:00 +0000 http://premium.wpmudev.org/blog/?p=135901 A few years ago, responsiveness was considered an added bonus as a WordPress theme feature, but things have changed. With up to 50% of visitors using tablets and smartphones to access websites, ensuring your site looks great on a variety of devices is no longer just nice to have but essential.

This is reflected in the fact that a huge number of WordPress themes are responsive. At the time of writing, a search in the WordPress Theme Repository found no less than 861 themes – that’s nearly 30% of all available themes.

But just because a theme’s responsive doesn’t necessarily mean it will work for you. So how do you navigate your way through hundreds of responsive themes to find the right one for you?

Hopefully this post will help you. I’ve looked at 10 of the most popular responsive themes in the theme repository and reviewed them using five criteria:

  • Performance on a variety of screen sizes and devices, not just standard sized smartphones.
  • User Interface on a variety of screen sizes and devices. Responsiveness isn’t just abut resizing content to fit into different screen sizes. I looked at the UI for each theme and how easy it is to use on small screens using touch as well as large screens with a mouse.
  • Usability (including how easy it is for administrators to work with the theme on a mobile device).
  • Flexibility – how easy is it to customize the theme and get it working and looking how you want it to?
  • Design – with a focus on how the design supports the content on all screen sizes as well as how good looking it is.

Note: While there are more than 800 responsive themes available, I’m limited to how many I can review. If I’ve missed one that you’ve worked with and rate highly, please add it in the comments with some information on what’s good about it – I can’t add it to this review, but anything you add will help inform other readers.

Twenty Fifteen


WPMU Rating


The Good

  • Resizes to all screen sizes
  • Navigation menu transforms to a tappable link on smaller screens
  • Header image moves to sidebar on wider screens; header on smaller screens
  • Sidebar widget area moves to tappable link with the navigation menu on small screens

The Bad

  • Header image placed behind sidebar text on large screens affects legibility of text
  • Uses the theme customizer in place of options screens which affects admin usability on small screens
  • Only one widget area in the sidebar: nothing in the footer
  • Sidebar widgets are difficult to find on small screens


  • Cross-device performance: 4/5
  • Cross-device UI: 3/5
  • Usability: 3/5
  • Flexibility: 2/5
  • Design: 2.5/5
  • Overall: 2.9/5

The Bottom Line

The new default theme, released with WordPress 4.1, is responsive, as were its predecessors. However, despite having a responsive layout it doesn't offer much else in terms of mobile UX and treats widgets in a way which I found confusing on small screens. There's only one widget area, in the sidebar, which is also where the navigation menu appears. On small screens, both of these disappear and are accessible via a menu button at the top right of the screen. I like this approach for navigation, but for widgets it can be confusing as for many sites these are part of the content and need to be always visible.

I'm also concerned about the fact that the header image sits behind the sidebar (on wide screens) or header (on small screens) and makes the text in those areas very difficult to read: an option to alter the opacity of the image would help here, or to turn it off for small or large screens.



WPMU Rating


The Good

  • Resized to all screen sizes tested
  • Slideshow resizes effectively on all screen sizes and orientations
  • Navigation menu converts to a tappable link on small screens
  • Customize fronts with Google Fonts
  • Customize the color scheme with one of 17 predefined skins
  • Option to add social links
  • Option to enable retina support for images

The Bad

  • Skins are limited: no option to fine tune specific colors
  • No option to turn items (such as slideshows) on and off for different screen sizes
  • A few issues with headings parsing onto two lines neatly on small screens
  • Exclusive use of the theme customizer makes it difficult to administer the theme on a mobile device


  • Cross-device Performance: 4.5/5
  • Cross-device UI: 4/5
  • Usability: 2.5/5
  • Flexibility: 4/5
  • Design: 4.5/5
  • Overall: 3.9/5

The Bottom Line

Customizr is a very popular theme which doesn't sell itself specifically on being responsive but it is, so warrants a look.

The theme uses the WordPress theme customizer for all of its customizations, with no theme options or settings screens. This has the advantage of displaying your changes as you make them, but limits the amount of customization that can be added and also makes it very difficult to make customizations on a mobile device (although this isn't the theme developer's fault!).

I was disappointed that there were no options to turn page elements on or off for different screen sizes, but impressed with the way the layout adapted to a wide range of screen sizes.



WPMU Rating


The Good

  • Layout consists of areas which resize and move position on smaller screens
  • Navigation menu changes to a full width button on small screens
  • Multiple navigation menu locations all of which are responsive
  • Multiple widget areas for different screen locations and content types
  • Option to use an entirely widget-based home page, which is fully responsive
  • Options screens in admin which are fully responsive

The Bad

  • Only way to customize colors or design is with custom CSS
  • No option to change layout or hide elements on different screen sizes


  • Cross-device Performance: 4.5/5
  • Cross-device UI: 4/5
  • Usability: 4.5/5
  • Flexibility: 4/5
  • Design: 4/5
  • Overall: 4.2/5

The Bottom Line

Naming your theme "Responsive" is a pretty brave thing to do and this theme mostly lives up to expectations.

Its options screens are responsive, meaning you can administer it on a mobile device, and its simple, modern layout adjusts perfectly to different screen sizes. The number of widget areas and built in menus is impressive, especially as multiple menus can be very useful on different screen sizes. It would be helpful if each of these could be switched on or off for larger or smaller screens.

It includes a range of customization options but it's a shame the color scheme can only be altered by adding your own custom CSS and that screen elements can't be turned on or off for different screen sizes.



WPMU Rating


The Good

  • Layout responds to all screen sizes tested
  • Navigation menu converts to a dropdown list using native device features
  • Can be customized from the front-end
  • Layout customisation options
  • Sidebar moves below content on small screens (but is unreliable if you activate dynamic scrolling)

The Bad

  • Slider is hidden from mobile devices using media queries, not PHP (so images are still downloaded)
  • Combination of square and rounded corners means post headings look untidy on small screens
  • Admin should be possible on small screens because the them uses options screens instead of the theme customiser, but is impossible because of a fixed position header being in the way
  • Design customisation is limited to adding custom CSS


  • Cross-device performance: 3.5/5
  • Cross-device UI: 3.5/5
  • Usability: 2.5/5
  • Flexibility: 2.5/5
  • Design: 2.5/5
  • Overall: 2.9/5

The Bottom Line

Medicine is an interesting theme because on small screens its design resembles that of mobile plugins such as WP-Touch, which were once so popular. The fact that it uses options screens instead of the theme customizer is encouraging for admins working on small screens; however, the presence of a fixed position header at the top of every options screen makes it impossible to access the controls and settings below on small screens.

Overall the design is unexciting but is focused on content, and the fact that the slider is hidden on small screens is good (but would be better is this was achieved using PHP instead of CSS, so that the images weren't downloaded by your phone anyway). It would be improved by some color selection options.



WPMU Rating


The Good

  • Content resizes to all screen sizes tested
  • Slider resizes and displays or hides text according to screen size
  • Navigation menu converts to a tappable button at top right on small screens
  • Multiple widget areas
  • Clean, modern design with ultra-thin fonts which are different from the norm but are still legible on different screen sizes.

The Bad

  • The small screen navigation menu is a bit clunky and not as well designed as the rest of the layout
  • Very limited color options - all you can change via the customizer is the background color


  • Cross-device Performance: 4/5
  • Cross-device UI: 3/5
  • Usability: 2/5
  • Flexibility: 2.5/5
  • Design: 3.5/5
  • Overall: 3/5

The Bottom Line

The Colorway theme has a truly responsive layout, with page elements resizing nicely on different screen sizes. However, given that its name is Colorway, the options for customizing your site's colors are extremely disappointing. You can change the background color in the theme customizer but if you want to amend anything else, you'll need to add custom CSS.

The navigation menu behaves as you'd expect it to, but unfortunately the design of the menu on small screens isn't very attractive; or at least not as attractive as the rest of the theme's design: it feels like a bit of a last minute add-on. The options screen isn't ideal either: it's not responsive so is impossible to use on small screens.

However, the way the slider behaves on different screen sizes is very well designed and widget areas are responsive, moving to the locations on the screen that you'd expect them to. The slider could be improved by adding some customization options for different screen sizes.



WPMU Rating


The Good

  • Resizes to all screen sizes tested
  • Multiple navigation menu options with the option to have mobile-specific navigation
  • Lots of theme options including some specific to mobile devices
  • Option to amend colors using color picker and fonts using Google onts
  • Theme options screen is responsive meaning admin can be done on small screens

The Bad

  • Large featured images get in the way on small screens
  • Margins on small screens are sometimes a bit too small for the content to breathe
  • Layout suited to smartphones kicks in at a wider screen width, meaning that the layout is too sparse on tablets


  • Cross-device Performance: 3.5/5
  • Cross-device UI: 3.5/5
  • Usability: 4.5/5
  • Flexibility: 4/5
  • Design: 3/5
  • Overall: 3.7/5

The Bottom Line

This theme has possibly the most impressive range of options of the themes reviewed here, made even better by the fact that it uses a responsive options screen so you can work with the theme on a mobile device. It also includes the option to vary features such as the menus and slider on mobile.

It is let down to some extent by the design – it's a bit bare and the breakpoints target screen sizes which are too wide, meaning that on tablets you'll be looking at a layout which seems to be designed for smaller screens. The addition of a couple of extra breakpoints would be a big improvement.



WPMU Rating


The Good

  • Resizes to all screen sizes tested – with thought clearly put into the design at different screen widths
  • Options to select one of 20 skins to customize color scheme
  • Sidebar and footer widget areas
  • Option to easily customize metadata shown with posts
  • Alternate home page layouts to choose from
  • Home page settings for each layout including text and images
  • Menu converts to dropdown on small screens using device's native features

The Bad

  • Theme options screen doesn't use familiar WordPress UI and isn't responsive
  • Breakpoints are set for tablets but the layout they give is more suited to smaller screens
  • No option to turn elements on or off on mobile devices


  • Cross-Device Performance: 4/5
  • Cross-Device UI: 4/5
  • Usability: 1.5/5
  • Flexibility: 4/5
  • Design: 4/5
  • Overall: 3.5/5

The Bottom Line

This theme is aimed at business users and provides a modern, eye-catching design, which will be well-suited to business sites. The design and layout have clearly been thought out for smaller screen sizes and it looks great on smartphones. However, the layout for smaller tablets (or for larger tablets in portrait orientation) is more suited to smaller screens, with items arranged in columns where they were side-by-side on large screens.

The theme options UI isn't very easy to work with: it's got custom styling so is unfamiliar and some of the controls have very low contrast. It's also not responsive. But the design for small screens and the range of design and content options make this a powerful theme, which is well worth considering, especially for business sites.



WPMU Rating


The Good

  • Multiple breakpoints for different screen widths means it looks great on tablets as well as smartphones
  • Multiple layouts to select from
  • Two color scheme options
  • Social links
  • Multiple widget areas – not just in sidebar and footer
  • Five extra widgets bundled (although purists may argue that widgets shouldn't be a part of a theme!)
  • Navigation menu converts to dropdown list on small screens using native device feature
  • Home page content can be added via a widget

The Bad

  • Theme options screen uses unfamiliar UI and isn't responsive
  • No option to switch elements of and on for different devices
  • The design uses heavy fonts and dull colors and feels a little outdated

  • Cross-device Performance: 5/5
  • Cross-device UI: 4/5
  • Usability: 2.5/5
  • Flexibility: 4/5
  • Design: 2/5
  • Overall: 3.5/5

The Bottom Line

Unlike most of the other responsive themes I've looked at, this one has multiple breakpoints, which aren't just targeted at the smallest screens. It also includes multiple widget areas and some options for layout and color scheme.

However the admin UI isn't great – it doesn't use the familiar WordPress UI and the theme options screens aren't responsive, meaning they're difficult to work with on mobile devices. The design could do with an update, too – it feels a little heavy and outdated. But if you're looking for a theme which resizes nicely on tablets, this could be a good one to choose.



WPMU Rating


The Good

  • Resizes to all screen sizes tested
  • Navigation menu converts to dropdown list on small screens using native device features
  • Range of options including layout, slider and social
  • Theme options screens are responsive so work on small screens
  • Optimised for retina displays

The Bad

  • Breakpoints are targeted at desktops and smartphones – no layout for tablets
  • No options to change color scheme
  • No option to turn features on or off on mobile devices


  • Cross-device Performance: 3.5/5
  • Cross-device UI: 4/5
  • Usability: 4/5
  • Flexibility: 3/5
  • Design: 3.5/5
  • Overall: 3.6/5

The Bottom Line

Market is an e-commerce theme, which is responsive but could look better on tablets. On an iPad in portrait orientation, for example, it uses a layout designed for smaller screens with a lot of space around the elements. However, its options screens are responsive so you can administer your site on mobile devices. It's optimized for retina displays but doesn't give you the option to upload higher resolution photographs for those displays, and doesn't give you any options for turning features or elements on or off in small screens.

The design is clean and doesn't distract from the product images, which is what it's designed to showcase. However, it could be improved by an option to amend the header text color, which is the one blue element in an otherwise completely monochrome design.



WPMU Rating


The Good

  • Grid-based layout adapts at multiple breakpoints, so looks great on smartphones, tablets and desktops
  • Navigation menu converts to a tappable link on small screens
  • Option to hide sidebar and footer widget areas on mobile devices
  • Layout options – customize the total number of columns
  • Flexible color scheme options using a series of color pickers
  • Theme options screens are responsive
  • Social links buttons
  • Choice of fonts for headings and body text as well as option to resize text
  • Minimal, modern design which looks professional
  • Multiple widget areas for locations on the page and different content type

The Bad

  • An extra breakpoint for larger screens would be a bonus


  • Cross-device Performance: 5/5
  • Cross-device UI: 4.5/5
  • Usability: 5/5
  • Flexibility: 4/5
  • Design: 4/5
  • Overall: 4.5/5

The Bottom Line

Pinboard is another theme with a grid-based layout. The number of columns in the grid and the positioning of boxes change according to the screen width, and there are multiple breakpoints so your site will look great on tablets as well as smartphones. The only failing is that the layout looks a bit lost on very large screens.

The theme lets you customize fonts, colors and font sizes as well as selecting form layout options and specifying how many columns to use on the widest screens. There are multiple widget areas (including ones for the home page and 404 page) and you can select whether widget areas are displayed on mobile devices.

All in all this is a great responsive theme with enough customization options to allow you to make it your own (but don't go overboard!) and a truly responsive layout that works on all screen sizes.


There are a great many responsive themes out there, but finding ones that offer more than a layout and resizes to the smallest screen sizes isn’t necessarily easy.

The best themes in this list have multiple breakpoints so that they make the most of other screen sizes such as those of tablets (both large and small). The best responsive themes will also have a range of options for you to customize your site and let you specify whether your site will work differently on mobile devices.

  • Overall Ratings
  • Twenty Fifteen: 2.9/5
  • Customizr: 3.9/5
  • Responsive: 4.2/5
  • Medicine: 2.9/5
  • Colorway: 3/5
  • Virtue: 3.7/5
  • Alexandria: 3.5/5
  • Designfolio: 3.5/5
  • Market: 3.6/5
  • Pinboard: 4.5/5

I’ve rated the design of each theme but this will be a subjective judgement and you may find that those themes whose design I haven’t rated highly works better for your site. However, I would recommend choosing a theme with a minimal, modern design that ensures content isn’t crowded out on small screens.

http://premium.wpmudev.org/blog/free-responsive-wordpress-themes-reviewed/feed/ 3
Using a Custom Taxonomy to Add a Location Drop Down http://premium.wpmudev.org/blog/custom-taxonomy-location-drop-down/ http://premium.wpmudev.org/blog/custom-taxonomy-location-drop-down/#comments Sun, 18 Jan 2015 13:00:00 +0000 http://premium.wpmudev.org/blog/?p=136303 Recently in the support forums, one of our members wanted to add US states to his Directory listings and make his listings searchable by state.

While there are plugins that can do this, we chose a more interesting path that takes advantage of our plugins.

In today’s Weekend WordPress Project I’m going to show you how to use a custom taxonomy to add a location drop down to your site.

Plugins You Will Need for This Project

These are the plugins you’ll need for this project:

1. Create New Taxonomy for Your States/Locations

In CustomPress, navigate to the Taxonomies tab, and select Add New.

Add taxonomy.

Assign your taxonomy’s system name, which, like a slug, should be all lowercase letters. I’m going to call my “state.”

Taxonomy name

Assign your taxonomy to the relevant post types. For my example here, I added the “states” taxonomy to both Directory Listing and Classified custom post types.

Post type

Change any of the labels referring to your taxonomy in the box called “Labels.”


Set the following settings to “true” if they aren’t already:

  • Show Admin Column
  • Public
  • Show UI
  • Show in Nav Menus
  • Hierarchical

And don’t forget to hit “Save.”

2. Add Your States or Locations

Next, navigate to Listings (or whichever plugin you’re using) > States (or your label) and add each location, just like adding a list of categories for standard posts.

Check to make sure everything is working as planned by going to Listings > Add New, and ensure you’ve got a shiny new location dropdown on the edit post screen.

Add new listing.

If everything looks cherry, move on to the next step.

3. Enable Search by State/Location

The screenshots below are using Advanced Custom Post Search, your search plugin may look a bit different behind the scenes.

First, select the post type you’d like the search to apply to. In this case, I chose the Directory custom post type.

Next, select which taxonomies you would like the search to use. Here, I selected listing category and state.

Customize the other settings to your liking, and hit “Save.”

Listing search.

4. Add to Your Site

Advanced Custom Search comes with both a handy widget and a shortcode, which allow you to place the search tool wherever you’d like. I used Custom Sidebars Pro to create a sidebar for my Listings pages with a list of the most recent Listings underneath the Advanced Custom Search widget.

Listing search.

That’s it! Now if you’d like to make your Listings or Classified (or more!) custom posts available and searchable by state, you’ve got all the tools you need.

What kinds of cool stuff have you done with CustomPress and custom post types? Let us know in the comments below.

http://premium.wpmudev.org/blog/custom-taxonomy-location-drop-down/feed/ 2
5 Simple Methods for Creating Custom Queries in WordPress http://premium.wpmudev.org/blog/creating-custom-queries-wordpress/ http://premium.wpmudev.org/blog/creating-custom-queries-wordpress/#comments Fri, 16 Jan 2015 13:00:27 +0000 http://premium.wpmudev.org/blog/?p=136037 On every page of your website, WordPress runs a query. This fetches data from your site’s database and then displays it in the way your theme tells it to using the loop. This is referred to as the main query.

Depending on the type of page being displayed, WordPress will use the most appropriate template file, meaning that the loop might vary for different content types. But it will always run a query to fetch data from the database.

Sometimes you may want to change the way the query works. For example, on your main blog page you may want to exclude posts in a certain category, or on an archive page you may want to list posts by category rather than by date order. You could also decide you need to add extra queries to your pages, adding lists of recent posts or related posts, for example. Or you may want to create a template file which replaces the main query with a completely custom one.

The great news is that WordPress makes this possible. There are a few methods you can use to either modify the main query or create a new one.

In this post I’ll look at:

  • Scenarios in which you might need a custom query, focusing on which require customizing the main query and which require a whole new query, and
  • The five methods for creating custom queries (including one you shouldn’t use, and why).

Before You Start: Understanding the Basics

If you haven’t created custom queries before, there are a few terms you’ll need to understand. If you’ve worked with theme template files or queries before, you can skip this bit!

  • A query is a routine, which WordPress runs to fetch data from your site’s database. This will include posts, attachments, comments, pages, or any content that you’ve added to your site.
  • The loop is code your theme (or sometimes a plugin) used to specify how the results of the query will be displayed on the page. So for example on your main blog page the loop might include the title of each post, a extract, a featured image maybe, and a link to the post’s own page (called the permalink).
  • Template files are used by your theme to display pages for each content type. Different themes have different template files, but they must include a main index.php file and will often also include a page.php file for static pages, a single.php file for single posts, and archive.php file for archive pages and maybe a category.php file and tag.php file for category and tag archives respectively. There are more template files themes can use, for example to dimply taxonomy or post type archives – for more details see the Template Hierarchy.
  • Conditional tags can be used in your template files or by plugins to check what kind of page is currently being displayed. For example is_page() checks if a static page is being displayed and is_home() checks if we’re on the home page. There are plenty more conditional tags including ones for whether the user is logged in and more.

When You’ll Need a Custom Query

There are two types of custom query:

  • The main query as called by WordPress, but with changes that you’ve made to it, and
  • A completely new query to fetch different or extra content.

Let’s take a look at when you might use each.

Modifying the Main Query

This is something you’d do if you want your page to display the results of the main query for that content type, but you want to make some tweaks to it. You don’t want to show completely different content and you don’t want to add an extra loop.

Examples of this might include:

  • On your main blog page, displaying custom post types as well as posts
  • On a category archive page, only displaying posts of one post type
  • On a category archive page, ordering the posts displayed alphabetically instead of by date

There are plenty more possibilities, but as you can see, this is about making minimal changes to what’s queried or to the way in which it’s output.

Later in this post, I’ll show you how to achieve all of the above.

Writing a New Query

If amending the main query isn’t enough, you’ll need to create a new query. This gives you much more flexibility but shouldn’t be used when you just want to modify the main query, as it’s less efficient. You would create a new query if you want more than one loop on a page or if you want to overwrite the main query with a completely new one.

Examples of when you might need to create a new query are many and varied, but include:

  • Running two loops on an archive page: one for the first post and another for all subsequent posts. You would do this if you want to display different content for the first post, for example if you want to include an excerpt or featured image for the first post but not for the others. Note that if all you want to do is style the first post differently, it’s unlikely you’d need multiple loops: instead you should be able to use CSS targeting the first post.
  • On a single post page, running an extra loop to display other recent posts (or featured posts) below the post content, to encourage your readers to read more.
  • Adding a banner linking to a single featured post (or to all featured posts) at the top of each of your pages, for example if you’ve added a post promoting a new product. This gives you more flexibility than adding a static banner as you can change the post used more easily.
  • Creating a list of pages in the same section of the site, if your site has a structure based on hierarchical pages. You might want to put this in the sidebar.
  • Creating a page template with a completely custom query to display posts by taxonomy or post type (or maybe both, in a grid).
  • On a post type archive page, listing posts by category or taxonomy term rather than by date (for example creating columns or boxes with links to recent posts in each category).
  • Creating a banner in your sidebar to link to the most recent post and display its featured image.
  • Creating a page to list posts with a specified term in more than one taxonomy (e.g. on a movie site, listing sci-fi films made in the USA, with genre and country each being a taxonomy).
  • Creating a post type for sidebar content and querying posts of that post type in the sidebar. This would help non-coders to add content to the sidebar with more flexibility than they can get from widgets.

There will be many more scenarios that I haven’t included here, but this gives you an idea. I won’t be showing you how to achieve each of these in this post as there would be way too much to cover, but I will give some examples.

The Methods for Creating a Custom Query

There are five methods for creating custom queries, and they can be split according to whether they help you modify the main query or create a new one. The methods for modifying the main query are:

  • Using the pre_get_posts action hook. This lets you make modifications to the main query by adding a function to your theme’s functions file or via a plugin (not in your theme template files). You can combine it with a conditional statement to ensure it only runs on pages displaying certain content types.
  • Using query_posts(). I’ve included this here partly for completeness but more importantly to explain why you shouldn’t use it. query_posts() is an inefficient and potentially unreliable way of amending the main query. Instead of actually amending the main query it fetches the main query then chucks it out and starts again, rerunning the main query with your changes. This will slow down your site. It’s also unreliable and can break, especially when pagination is needed. So don’t use it!!

The three remaining methods all let you create a new query:

  • The WP_Query class. This is the most powerful and flexible way to create a new query, and you would use it when creating a second loop in a template file or when creating a template file with a completely custom query replacing the main loop. You have to be careful when using it: the main risk is if you don’t reset the query after running your loop, which means that WordPress won’t be able to correctly identify what page type is being displayed. But you can easily get round this.
  • The get_posts() template tag. You would use this in a template file (including your sidebar or footer for example) to fetch a list of posts. It uses the WP_Query class to do this, so is in effect a simpler way of using that if all you need is posts. You can use parameters with it to specify which posts you want.
  • The get_pages() template tag. This works in the same way as get_posts(), fetching pages instead of posts.

So now you know what the five methods are, let’s take a look at each of the recommended ones in detail.

The pre_get_posts Action Hook

pre_get_posts is an action hook, which means you attach a function to it to make something happen at the time that WordPress runs the pre_get_posts action. As you might expect, WordPress runs this action immediately prior to fetching posts from the database, so any function you attach to it will affect how WordPress does that.

To use pre_get_posts, you create a function and then hook it to the action, like so:

Let’s take a look at what this does:

  • Firstly, it creates a function called my_function. What the function does is contained within the braces.
  • Next, it attaches that function to the pre_get_posts hook using the add_action() function. Without this, your function won’t work.

In addition to this, you almost always need tho include a conditional tag inside your function. Without this, WordPress will run your function every time it fetches posts, including when you’re working on your posts in the admin. So your function will look like this:

Above I’ve checked that we’re not in the admin screens and also that the query being run is the main query. It’s important to check WordPress is running the main query as it might cause problems if you run your function for extra queries you’ve created. You can add extra conditional tags here as we’ll see. Let’s flesh this out a bit with some examples.

Including Custom Post Types On Your Main Blog Page

By default, WordPress only lists posts on the homepage. If you create a custom post type, it’ll assume you want to display those elsewhere and not include them here. But sometimes you may want to display more than one post type on the home page, in which case you use the pre_get_posts hook.

To do this, you add the following to your theme’s functions.php file or to a plugin you create:

This checks for two things: is this the main query and is it the home page (using is_home()). Then it sets the query to include two post types: 'post' and 'custom_post_type', being your custom post type. Note that you must include 'post' here if you still want the home page to display posts as well as your custom post type. If you just added 'custom_post_type' here, this would override the default and just show posts of your custom post type. Sometimes you might want to do that but this isn’t one of those times.

You can read about this technique in more detail in this post.

Display Posts of a Custom Post Type on a Category Archive Page

This example assumes that when you registered your custom post type, you gave it support for categories and that you’ve assigned categories to posts of your custom post type. To amend your category archives to display posts of your custom post type, you use the following:

This checks if the main query is being run and if we’re on a category archive using is_category(). It then modifies the query to fetch posts of your custom post type. Note that because I haven’t included 'post' here, ordinary posts won’t be displayed on any category archives, and that I don’t need to use an array as I’m only specifying one post type.

If you wanted to be more specific when using this method, you could check for a particular category:

This will modify the main query only on the 'category-slug' archive page, where 'category-slug' is the slug for your category.

Changing the Way Posts Are Ordered

Our final example deals not with what data is queried but with how it’s output. Let’s say that on your category archive pages you don’t want to display posts by date, but in alphabetical order. You can do this using pre_get_posts as follows:

This uses two query parameters: orderby and order, to modify both what posts are sorted by and the order in which they’re displayed. For more parameters you can use with pre_get_posts, see the WordPress Codex page for WP_Query, which uses the same parameters.

The WP_Query Class

The WP_Query class is the most powerful method available for writing a custom query. Use it when you want to replace the main query with a new one or when you want to add a new query in addition to the main query.

WP_Query has parts:

  • The arguments for the query, using parameters similar to the ones you might use for pre_get_posts
  • The query itself
  • The loop
  • Cleaning up: closing if and while tags and resetting post data.

This will look something like the following:

As you can see, this is more complicated than using pre_get_posts, which is one of the reasons you should avoid using it if you want to modify the main query. But the main reason for this is because that would work WordPress harder and slow your site down.

Let’s take a look at an example. Let’s say I want to add a second loop after the post content on my single.php template file, to display a list of featured posts. I’ve defined those featured posts using a “featured” category. For each of these posts I want to display the featured image and title, with links to the post.

Here’s how I do it:

This uses three arguments to query data:

  • 'post_type' => 'post' fetches just posts
  • 'posts_per_page' => '4' only fetches four posts
  • 'post__not_in' => array( $post->ID ) ensures that the post currently being displayed isn’t included.

It then outputs the four posts in a loop which displays the featured image and the title, each inside a link to the post’s page. You could then use CSS to style these, placing them side by side or in a grid and overlaying the title over the image.

The get_posts() Template Tag

If you don’t need as much flexibility as you get from WP_Query, you might find that get_posts() does what you need. In fact, I could have used it for the example above. get_posts() is a template tag which accesses the WP_Query class, and you can use it in a similar way to WP_Query.

So, to create that list of four recent posts that I created above with WP_Query, you’d use get_posts() in the following way:

The eagle-eyed amongst you will spot that this is very similar to the code I used with WP_Query above. However if you’re really observant you’ll have spotted a few differences:

  • The arguments don’t have to include the post type
  • I use a $posts variable to store the array output by get_posts()
  • Instead of checking if the query has posts I use if( $posts ) to check if it’s got anything in it
  • Instead of a standard loop I use foreach ( $posts as $post ), which loops through each row in the array
  • To access all of the post data I want, I include setup_postdat( $post ).

As get_posts() uses WP_Query, there really isn’t much difference between the two so I tend to use WP_Query as it gives me more flexibility (and because I’m used to using it with custom post types). However where I find get_posts() most useful is if I simply want to check if there are any posts with my arguments. I can then output code depending on whether there are any posts present, which doesn’t have to be a loop.

The get_pages() Template Tag

get_pages() is very similar to get_posts(): it uses WP_Query but it fetches static pages instead of posts. Let’s look at an example where you might use it.

Let’s say your site has a set of top level pages which are most important and you want to add a list of these in the sidebar so you can style their links and encourage visitors to go to those pages. In your sidebar.php template file, you’d add this code:

Let’s take a look through this:

  • First I define my arguments – 'parent' => 0 retrieves pages with no parent, while the other two arguments define how the pages are sorted.
  • I then use get_pages() to populate an array stored as $pages
  • I check if $pages has any data using if( $pages )
  • If so, I open a list, then for each page I open a list item
  • Instead of using setup_postdata() like I did with get_pages(), I make direct reference to the $post variable with different template tags that will output the link and the title. I have to use these because I haven’t used setup_postdata().
  • Because I didn’t use setup_postdata() I don’t have to use wp_reset_postdata().

The code above is a more efficient way of outputting a list of pages than if I’d used WP_Query in all its glory.


Being able to modify the main query or write your own queries is a very useful skill to develop if you’re planning on creating custom themes or plugins, or developing complex, data-driven sites for clients.

I use one form of custom query or another in almost every site I build, and in my view it’s one of the most exciting things about WordPress (but you may have your own favorites!)

As I’ve demonstrated here, there are five ways you could potentially create custom queries, although only four of these should be used. These are:

  • pre_get_posts for modifying the main query
  • WP_Query for creating complex custom queries
  • get_posts() and get_pages() for simpler custom queries retrieving just posts or pages.

A combination of these will help you to create advanced WordPress sites and display data however you need to.

Do you use custom queries? What are your top tips for creating custom queries? Let us know in the comments below.

http://premium.wpmudev.org/blog/creating-custom-queries-wordpress/feed/ 1
Getting Started with WordPress Plugin Development: The Ultimate Guide http://premium.wpmudev.org/blog/wordpress-plugin-development-guide/ http://premium.wpmudev.org/blog/wordpress-plugin-development-guide/#comments Thu, 15 Jan 2015 12:00:00 +0000 http://premium.wpmudev.org/blog/?p=135118 Plugins are PHP scripts that alter your website – basically, bits (or even lots!) of code that can be uploaded to your WordPress install to extend and expand the functionality of your site, without having to hack the core code.

The great thing about plugins is that they allow you to add features to your site and remain intact, even if you switch themes or upgrade your WordPress install.

Creating a plugin of your own is really not that difficult and can solve a lot of problems. Copying and pasting useful code and additional features into your theme’s functions.php file is great, but these changes may be lost when you update your theme. A plugin is a safe way to try out new things and the way to go if you need to implement cross-theme functions.

This article will walk you through creating a plugin, and we’ll also look at some intermediate/advanced concepts:

  1. Creating a simple plugin integrating WordPress with Facebook Open Graph.
  2. How plugins work.
  3. Using hooks.
  4. Getting started with filters.
  5. Adding scripts and styles.
  6. Creating a plugin settings page.
  7. Enabling translations.

Note: This guide is aimed at those who are getting started with plugin development. A little knowledge of editing files and some rudimentary HTML and PHP is all you’ll need to follow along.

A Simple Plugin Project

In this article we’re going to create a plugin that integrates WordPress and Facebook Open Graph. Open Graph tags are special HTML tags, which give Facebook the information it needs to share your page and ensure it looks great.

Here’s a set of example tags, which could be used on the page you are reading right now:

You can read all about Facebook Open Graph and Facebook Content Sharing Best Practices on the Facebook site.

For this project, we need to make sure that whenever a single blog article is shown, Open Graph tags are added to the header of our website. Site heads consists mostly of metadata and other hidden bits of information, and are added between the <head> and </head> tags in an HTML document.

The next part of this article will focus on getting this done. After this example, I’ll venture more deeply into plugin development territory.

Creating a New Plugin

The first thing you need to do is create a folder to store your plugin. Go to the wp-content/plugins/ directory in your WordPress installation and create a folder called my-facebook-tags. Keep in mind that whatever you name your plugin’s folder will be your plugin’s slug.

A plugin slug should be unique throughout the WordPress Plugin Repository if you want to upload it and make it publicly available. What this means is that no other plugin created by anyone else should have this slug. You can search for existing plugin slugs easily, just use Google!

Keep in mind that the plugin’s name is not necessarily the same as its slug. Take a look at the iThemes Security plugin. The last bit of the URL is the slug: better-wp-security. The name of the plugin, however, is iThemes Security.

If you’re just making a plugin for yourself it is still important to make sure slugs don’t clash. During the lifetime of your website you will probably use a number of plugins and you don’t want one to accidentally clash with yours and cause problems on your site because of a naming conflict.

Now that you have your my-facebook-tags folder, create a new file inside and name it my-facebook-tags.php. This will be your main plugin file and its name should be the same as your plugin’s slug, with the PHP extension tacked on.

Open your plugin’s main file and paste in the following code:

This code is a PHP comment, which won’t be visible directly in the WordPress admin. WordPress does use the data within it to output the plugin’s name and some other data in the Plugins section of the backend. I’ve tailored this to my own website, so be sure to modify the plugin author and other strings as you see fit.

Once you’ve saved this file, congratulation are in order because you’re just create your first plugin! It does absolutely nothing, of course, but it should be available in the plugins section and you should be able to activate it – go ahead and do that now.

How Plugins Work

Let’s pause for a moment to look at how plugins work before we continue with our Facebook Open Graph project.

Plugins provide functionality with hooks, therefore understanding how they work is crucial. Let’s look at a real world analogue for hooks. You know those little diaries where the first sentence says: I am the diary of _________. The empty line is where you put your actual name.

The company could of course go through all the names and create prints of each one but it would not be economical and a lot of people would be left out. Also, what if you want to put “The Master Of The Galaxy” instead of your own name?

That blank line is a hook. Instead of being specifically printed for a person it prompts the user to add his/her own name. Hooks work something like this in WordPress, let’s look at an example.

Themes are required to add the following function to the header file: wp_head(). Within this function is a bit of code where WordPress says: If a plugin wants to put some code here they may do so. The wp_head hook allows us to output something in the head section of the page, which is exactly what we need. Let’s test this”

The first line of the snippet above tells WordPress that we would like to attach some functionality to the wp_head hook using the my_facebook_tags() function.

The second line of code creates that function and the third line echoes a simple string.

This should now be visible at the top of any theme you activate, as long as it defines that wp_head() function (defining it is a requirement). We’ll remove that echoed string soon since you should never display text in the head section.

For the sake of correctness let me mention two things. There are two types of hooks: actions and filters. In the case above we used an action which is obvious because we used the add_action() function. Actions run whenever WordPress detects the hook that calls them.

Filters are similar but they modify a bit of data which WordPress uses. A good example is the logout message that is shown. Instead of performing an action whenever a logout message is shown, a filter allows you to modify the logout message itself. We will not go into hooks in detail here. I recommend taking a look at our article, A Quick (and in-Depth) Guide to WordPress Hooks, or the WordPress Codex if you would like to learn more.

The last thing I want to mention here is that technically a hooked function gets executed when the do_action() or apply_filters() function is executed. The wp_head() function contains calls to these other functions within it – it is not the hook itself.

Completing Our Plugin

Based on the description above it’s pretty clear we need to add our Facebook meta tags using the wp_head hook.

Here’s the rest of the code needed for our plugin, followed by an explanation:

I’ve basically pasted our meta tags into the function as-is. The only things I needed to modify were the values to make sure they reflected the currently shown post. I used the is_single() conditional tag to make sure that the tags are only added when a single post is shown.

In order to use the title, excerpt, image, etc of the current post I used template tags. The only bit of trickery I used was to check if the post has a featured image before displaying the Facebook tag for it.

With this single function in place we’ve created something quite useful. All of the posts on your website should now have Facebook-friendly tags. You can make sure they’re set up properly using the Open Graph Debugger.

And now our plugin is complete. Let’s now look at some other plugin concepts.

The Right Hook For The Right Plot

Now that you know how to add things to the head section of your website, let’s look at inserting elements into other parts of your site.

Using actions is pretty easy. If you want to perform an action whenever WordPress does something, you are looking for a hook.

What about loading Google Analytics tracking on each page? This should be done in the footer. Perhaps themes define something similar to wp_head? Indeed they do. Using wp_footer you can output code at the bottom of the page. WordPress itself uses these two hooks to place scripts and styles in their correct places.

So far this has been easy because these are hooks you can kind of see in the theme. But how about more “hidden” cases? What if you would like to send a post’s author an email once their post is published. This screams “action” because you are saying: When WordPress publishes a post, then do something.

Finding these hooks has become a lot easier these past years. They are usually well named: user_register, publish_post, profile_update, etc. If you type “add user WordPress hook” into Google you will likely stumble upon “user_register” immediately. From there it’s just a matter of reading documentation. Let’s use publish_post to send authors an email when their posts are published. Here’s our code:

Note that when I used the add_action() function I specified two additional parameters. The third parameter is the priority, which dictates when the action is executed. You may want to add multiple functions into the same hook and WordPress itself might use it too internally. The higher the priority, the later the action is performed.

The fourth parameter states how many arguments are passed to your functions. This is something you need to look up since it is not obvious from the name of the action. You can either look at WordPress documentation, or look into the WordPress source code to see where it is defined – the former is definitely easier if you’re just starting out.

Inside the function I use the attributes of the post to get the authors email address and the title and link to the post. I construct a short message and use WordPress’ built in mailing function  wp_mail() to shoot a quick email.

Again, how did I know this existed? Google! While it is entirely possible to write your own mailer function, a quick search for “WordPress mail” will reveal this function in a jiffy.

Getting Started With Filters

I mentioned earlier that filters are similar to hooks, but they allow you to modify data before it is used instead of implementing an additional action. For this example, let’s change the error message you get in the login form when you type an incorrect password at www.example.com/wp-admin

Since there is an error message regardless of our plugin – we just want to modify it – chances are we’re looking at a filter. There is indeed a filter named “login_errors” so let’s leverage it and modify the message:

The first parameter of every function you add to a filter will always be the filtered data. If you return this without modifying it you will end up with the original functionality. In our case let’s always show the same error message. This can be useful if you want to hide the root of the error. If you enter a correct username but incorrect password WordPress actually tells you this, giving hackers a bit of information. By having a single error message this information is hidden.

Filters and actions are used extensively for almost everything in plugins so I urge you to take a look at them in depth and familiarize yourself with their mechanism. You can find out more at the WordPress Codex.

Adding Scripts And Styles

Chances are are that at some point you will want to add your own styling or JavaScript functionality. This can be done by enqueueing the asset in question. Enqueuing uses actions to add scripts and styles modularly, taking care of any dependencies in the process. Let’s add support for a Google Font, which is actually a stylesheet:

The action we use is horribly named because wp_enqueue_scripts is actually used to add both scripts and styles to the front-end. In the hooked function we use wp_enqueue_style() to add our style. The first parameter is the slug or handle of the script (this is up to you), and the second parameter is the URL of the script.

Using //url.com instead of http://url.com is a neat trick which allows browsers to grab the appropriate version of the script. If your connection uses https it will retrieve the HTTPS version, otherwise it will use the regular HTTP version.

You can, of course, load assets you’ve made and store within your plugin. Let’s load a custom script we’ve made using the enqueueing method:

The process is much the same but I’ve used more parameters in the wp_enqueue_script() function. The third parameter defines the dependencies of the script. WordPress makes sure to load all the dependencies properly so even if you enqueue a dependency later they will be loaded correctly. The fourth parameter is a version number you can choose yourself. These additional parameters are available for the wp_enqueue_style() function as well.

The fifth parameter, when set to true, instructs WordPress to load a script in the footer instead of the header. This is preferred if your scripts aren’t needed in the header specifically as it decreases loading times and optimizes JavaScript.

To learn more about enqueueing take a look at our article on Adding Scripts And Styles To WordPress The Right Way.

Creating a Plugin Settings Page

Many plugins call for some options the user can set. Perhaps you want to disable Facebook Open Graph tags on some posts, or even disable the author email when you publish posts have you written? Both of these these can be implemented using options.

There are a number of ways to go about creating options for yourself, including some options frameworks out there. For simple options its easier to do it ourselves, and we are here to learn, so lets get started.

The best method to use is an object oriented approach, but I will use a simpler approach here. Take a look at the Creating Options Pages in the WordPress Codex for both the simpler and the object oriented approaches.

The first thing we’ll do is create a menu entry in the backend where we can place our settings user interface:

Note that we’re using an action – of course – to do this. Whenever WordPress sees the admin_menu hook it executes all functions tied to it. We happened to add a function to it ourselves so it will take that into account when building the menu.

We use add_menu_page() to create a top-level menu entry. This function takes a number of arguments:

  1. Page title – used in the title tag of the page (shown in the browser bar) when it is displayed.
  2. Menu title – used in the menu on the left.
  3. Capability – the user level allowed to access the page.
  4. Menu slug – the slug used for the page in the URL.
  5. Function – the name of the function you will be using to output the content of the page.
  6. Icon – A url to an image or a Dashicons string.
  7. Position – The position of your item within the whole menu.

I’ve created the empty function my_plugin_settings_page() (you’ll notice I added this as the fifth parameter). I’ll also add the content of this function in just a moment. At this stage you should be able to see the new menu entry at the bottom of the menu.

Before we create the user interface for manipulating settings, let’s let WordPress know what settings we intend to use. This is called registering our settings. For this example let’s presume we want to create a place to store the contact information of some key staffers who are not a part of our web project, for example our accountant.

As you can see, I hook a function into admin_init, inside which I use register_setting() to add our options. The first parameter should be an option group, the second the actual option. I recommend using the same option group if you only have a few options.

So how in the World did I know that I need to use admin_init here? The WordPress Codex of course! In some cases the hook you need to use is obvious. In other cases you’ll need to look it up. In some cases you can use different hooks while retaining functionality. In these cases there is usually a recommended way of doing things. Always search in the Codex before you implement a hook and you’ll be just fine.

So now that we have our admin menu entry and we’ve registered our settings, let’s create a form to display the user interface. Paste the code below inside the empty my_plugin_settings_page() function:

There are three things to keep in mind when building a form like this:

  • Use the settings_fields() function, adding the option group as the first parameter. This outputs some hidden fields WordPress will use to save your data.
  • Use the option names you defined while registering them in the name parameter of the inputs.
  • Grab the value of a field using the get_option() function, passing it the option name as the first parameter
Settings Form
The settings form we created.

With that, you’re all done! WordPress takes care of saving everything since you are using the built-in Options API. Well done!

Enabling Translations

This is definitely not a priority when you’re creating plugins for yourself, but it is a good idea to get in the habit of translation readiness as it is good practice for any public plugin.

The basics are really very simple. Any time you output some text, wrap it in either the __() function or the _e() function. Use the former for returning the string, the later for echoing it. For example:

The first argument of the function is the string to translate, the second is the text domain. This should be the same as your plugin slug.

By using these functions you will allow others to translate your plugin into their own language. This is a simple procedure that can help so many, so why not do it? There is a little more to it than these two functions, but by knowing only the above you are 99% of the way there.

To learn more about translating plugins take a look at our article How To Create A Translatable Theme Or Plugin.


There are tons and tons of things you can do with plugins and almost as many ways you can create them. While I am a very strong advocate of WordPress standards and doing things just right (object oriented approach, in many cases), I urge everyone to experiment.

As long as you’re not creating a product for distribution, feel free to do whatever you like. Don’t worry about complicating your life with methodologies you don’t yet understand. Do your best to research hooks that can help you add your functionality and make things work in whatever way you can.

The knowledge to do things right always comes to you after you are able to do things wrong, so don’t be too bothered about the rules for now.

Good luck with creating your own plugins!

What are your ideas for WordPress plugins? What else would you like to learn about plugin development? Let us know in the comments below.

http://premium.wpmudev.org/blog/wordpress-plugin-development-guide/feed/ 10
Your Totally Complete Guide to Customizing the WordPress Post Editor http://premium.wpmudev.org/blog/customizing-wordpress-post-editor/ http://premium.wpmudev.org/blog/customizing-wordpress-post-editor/#comments Wed, 14 Jan 2015 13:00:00 +0000 http://premium.wpmudev.org/blog/?p=135189 To give you a place to create posts and pages, WordPress uses TinyMCE, a platform independent web based Javascript HTML WYSIWYG editor control.

It offers a good, basic set of features that include bold, italic, quote, alignment, text color, paragraph style, etc. For the most part it does its job and it does it well. Your posts will look okay. They will use the CSS built into your theme, so you’ll have the basic fonts and styles. If you want a different font style, you’ll have to switch from the Visual editor to the Text editor and make your modifications in HTML. It works, but it’s time consuming and can be clunky.

But there is another option. You can use plugins or create your own code. Through using plugins or by coding by hand, TinyMCE can replaced or modified to give you more features to help you stand out from the crowd.

Plugins for Customizing the WordPress Editor

Of course plugins are much faster to deal with and get quicker results compared to writing your own code.

Here is a list of the best plugins to customize your WordPress editor. These plugins will give you some nifty features that can truly make your posts sparkle.

TinyMCE Advanced


This free plugin will let you add features to the WordPress WYSIWYG editor. You can rearrange, add, and remove buttons in the Editor’s toolbar. The tools you can add include: tables, options for inserting lists, find and replace, set font size and style, and more.

Some of the functions are easy enough just from the standard editor, but with the addition of tables and options for lists, this plugin gives you a lot of added functionality.

WP Edit


This plugin has a free and pro edition that gives you lots of added features, buttons, and options. The free edition alone has a lot of new features. It gives you a drag and drop function to create a custom top row of editor buttons. It also adds new editor buttons such as subscript, superscript, insert media, emoticons, search and replace, html editor, preview.

You can add a custom editor to excerpt areas, which even includes profiles. You can highlight posts and pages based on their status, use shortcodes in excerpts and widgets, and even import and export your settings if you want.

The Pro edition adds the Extreme Custom Widget Builder. This is a tool that lets you create custom widgets like posts or pages. You can insert them into the content area or into any widget area. It adds a drag and drop function to create custom buttons for any row of the editor. It also adds custom button arrangements based on user roles. It is WP Network Ready, so you can install it over the network. This plugin adds: an advanced code editor, custom editor styles, a format painter, advanced image editor, shortcodes to add columns, predefined styles, and much more.

It also includes one year of support and updates.

The single version is $35 and can be used on two sites. The Single Extended version is $69 and can be used on 5 sites. The Multisite version is $149 and can be used on an unlimited number of sites. The Developer version is $279 and adds reseller possibilities. All versions can be extended by one year at a fraction of their initial cost: $10, $20, $35, and $65.

Visual Editor Custom Buttons


The Visual Editor Custom Buttons plugin lets you add custom buttons to your WordPress editor. It simplifies the process of creating and customizing your buttons. You can add custom buttons using the Visual editor or the Text editor, add HTML code to your button, adjust the CSS, and view the affect in the visual editor. It comes with plenty of button icons built in, and of course you can add your own, too.

Plug-N-Edit Drag & Drop HTML Visual Editor with Web Page Builder WYSIWYG


This one is a free plugin with a drag and drop WYSIWYG editor to create your posts and pages. It uses an adaptive and responsive HTML editor for 3D page building to give you height, width, and depth, so you can layer your images, text, or whatever you want to place in your post. It will import your site’s CSS, so the pages you build with it will match the rest of your site.

You can create buttons, clone items, use Google fonts, and more. When you’re done editing, just save it and it places the code into your editor, where you can publish as normal. It has full access to your media, so you can use all of your images, videos, etc. It comes with images you can use as backgrounds in your posts, too.

Using this plugin takes you away from your WordPress editor, so it doesn’t make any changes to your editor other than adding a link. It gives you the option to use either editor, depending on your needs at the time.

This is an amazing plugin, especially considering it’s free. You can make some really nice layouts and posts with it. Using it is intuitive, so there’s not much of a learning curve.

CKEditor for WordPress


This one replaces your current editor and adds a ton of new buttons and features.

Features include buttons for cut, copy, paste as plain text, paste from Word, undo, redo, find, replace, select all, spell check (with options), numbered list, bullets, decrease indent, increase indent, block quote, alignment, text direction, language, link, anchor, more break, image, flash, table, horizontal line, smiley, special characters, iFrame, bold, italic, underline, subscript, superscript, remove format, format, font, size, text color, background color, maximize, and blocks. You got all that? Whew!

The toolbars are customizable. You can even customize the skin. This plugin has a built in read more button that shows up on the page where it will be seen on the screen when you mouse over it. It’s automatically inserted into the content but you can delete it if you want.

It can also integrate with several other plugins including Viper’s Video Quicktags, WP-Polls, GD Star Rating, and NextGEN Gallery. Unfortunately, it can’t be used with HTML editors such as the HTML Editor Syntax Highlighter. Instead, HTML is handled through its own editor, which looks really nice. It doesn’t color-code the tags for you though.



This free plugin is a WYSIWYG text editor that creates clean HTML code. This one is filled with intuitive features for your text. It has a configurable toolbar that bears similarity to the Microsoft Office Ribbon. It has four areas with tools: Common, Format, Paragraphs, and Insert.

Common covers your basics: copy, cut, paste, save, new, undo, delete, find and replace, etc. One really nice feature is the format painter. Paste from Word lets you insert clean HTML code from Microsoft Word, so you don’t get slow page-load times due to Word’s unnecessary markup. You can also paste from regular text.
Format is the text formatting functions: font style, size, bold, italic, underline, font color, back color, superscript, subscript, change case, remove format, select all, and clean up HTML. The feature for cleaning up HTML is a nice addition to help with speeding up your page load time.
Paragraphs contains all of the paragraph styling and formatting: It includes paragraphs, styles, justify, line height, left to right, right to left, line break, ordered list, bullets, outdent, indent, and block quote.
Insert adds even more functionality: It not only gives you an easy way to add your media, but also adds new features. It includes table, form, layout box, layer, fieldset, window, border, page properties, link, anchor, date and time, special characters, keyboard (for onscreen use – great for writing with a tablet or smartphone if you don’t want to use the one that’s built in to your device), image gallery, image, template, PDF, video, syntax highlighter, YouTube video, HTML5 tags, and Google Maps.
You can drag to resize the writing space in both height and width. At the bottom are tags to change from design, source, and preview.

These same features also appear on the back end for your comments. Readers can’t use them from the front end, though. You can turn this off in the settings if you wish.

Advanced settings let you choose the paths for your media so you can link your images, video, gallery, and documents to the Insert buttons.



Jetpack has a lot of features that add a lot to WordPress. Only a few of them modify your editor. One addition is the Contact Form. This feature will let you create a contact form that can be used in any post.

You can customize the fields, add as many fields as you want, and control how you receive the responses. You can customize your submit button and your notification emails. Plus, you can reuse any contact form you want by inserting a shortcode on the page.

Pods – Custom Content Types and Fields


Pods is a framework that makes it easy to add custom content and fields to your posts from your editor. The only modification that it makes to your editor is a single button to access your pods. This is a link that allows you to choose from the pre made content—or pods—that you’ve already made in another screen. It places a shortcode in your post that you can move around anywhere you want.

Just Writing


The Distraction Free Writing Mode in WordPress 4.2 is a great way to focus on just the text, but it could use a few more features. This is a plugin to enhance the distraction free editor and still keep it distraction free. It has drop down boxes where you can select paragraph and formatting styles, allowing you to see your text the way it will appear in the post.

Buttons include Visual, Text, bold, italic, strikethrough, underline, remove formatting, bullets, numbered list, image, link, alignment, outdent, indent, paragraph, proofread, insert more tag, undo, redo, save, preview, and exit. You can remove any of the buttons you want, so you can have even less on the screen to distract you if you want.

HTML Editor Syntax Highlighter


This is an excellent tool for those that like to write HTML code within their posts. Even simple code needs debugging and this plugin makes debugging from your WordPress editor a snap. You can code in full screen mode if you want.

It adds buttons for H1, H2, and H3 tags as well as comments. It removes the button for close tags because they are not needed when using this editor. Selecting Code will give you both sets of brackets (open and close) and will place your cursor within them. It displays line numbers for easy reference, too.

You can change the font size independently of the font that will be displayed in the post. The line you’re typing on is highlighted in blue, making it easier to see where you are in your code.

The main advantage to this plugin is the syntax highlighting. The code is color-coded to make your coding sessions much easier. It highlights the syntax, making the code much easier to read. The tags are colored green and your text is black.

You can save your posts by selecting crtl+s for PC and cmd+s for Mac.

There is a light and dark theme that you can switch between with a button click, so you can choose the one that’s the most comfortable to your eyes. Unfortunately, this plugin only affects the code in the post and page editor. For themes and plugins you will need a different plugin like Advanced Code Editor.

WP Editor


WP Editor is another plugin that adds features to the HTML coding side of your WordPress editor. It will replace your post and page editor as well as your plugin and theme editor. It gives you some great features for creating fast and clean code. It adds line numbers and color-codes your HTML so it’s easy to spot what is what. It has line wrapping, editor themes, search, full-screen mode, and FancyBox for image viewing. Additionally, it provides separate settings for the posts, plugins, and themes editors.


And speaking of code, rather than adding features via plugin, you can always code your own. Here are a list of tutorials from around the web that make it easy to add great features to TinyMCE.

Display the Full TinyMCE Editor in WordPress

First off, the TinyMCE features have been reduced in recent updates to make your visual editor cleaner. You can easily bring them back so you have full access to the full 26 kitchen sink buttons. This tutorial is from right here at WPMU DEV and shows you how to unhide the buttons with just a few lines of code. This one is just too easy to ignore.

To turn the buttons on, place this code in your functions.php file (code from Display the Full TinyMCE Editor In WordPress):

All 26 buttons will now be useable, opening up the full functionality of your visual editor.

The Post Editor with full array of buttons.

TinyMCE Custom Styles

TinyMCE has an API that can be used to make custom styles. These styles can be inserted into your posts from the Visual editor. This uses a hidden button called Styleselect. To use this, you will need to activate Styleselect and define your styles that will show in your pull-down menu. This code will go in your functions.php file or you can use it in a plugin.

NOTE: This code is taken from the WordPress Codex.

Enable the Stylesheet

This will activate the stylesheet pull-down menu in the Visual Editor. You enable the stylesheet by filtering the buttons that are loaded into TinyMCE. This tutorial will show you how to add these buttons to the second row, so the filter we will use is mce_buttons_2.

Registering Custom Styles

Once the stylesheet filter is in place, you have to register your styles. You can do this by using the style_formats array within your TinyMCE configuration array. This way you can register each style with several configuration settings.

Making Visual Editor Display Styles

In order to get your styles to display, they have to be registered in your CSS. For this you will use add_editor_style(). This will let you link a custom stylesheet file to your visual editor. The code looks like this:

Here’s what it looks like when added to the functions.php portion of your theme:

Next, you will need to create a file named custom-editor-style.css and place it in your themes root directory. Any CSS rules that you add to this file will then show up in your visual editor. Here’s an example of what this might look like:

Using Google Fonts

If you want to use Google Fonts, you can insert this code. This will bring in the styles from Google’s CSS file. It includes multiple variants of type-faces.

Reusing Your Theme Styles

If you want to use the styles from your theme’s stylesheet, you can import them into your custom editor stylesheet. This code goes into the custom-editor-style.css file:

WordPress WYSIWYG Editor Customization

This code from Alex Bulat will add four extra buttons to your Text editor. The buttons it will add are:

< p >, < br >, < h3 >, and < h4 >

This is a great solution for those that spend more time in the Text editor that the Visual editor.

To add these buttons to your text editor, add this code to your functions.php file:

This code will allow you to create your own button:

You would then change these parameters:

  • button ID
  • button value
  • button Tag Start
  • button Tag End

Add Custom Styles to Visual Editor

This code from WP Beginner shows you how to add your own custom styles drop-down menu to the visual editor so you can add buttons, content blocks, taglines, and more. The buttons allow you to choose your styles without having to switch between the visual and text editor.

Place this code into your function.php file. It will add a custom styles drop down menu to the second row of buttons on your visual editor.

Now that you have the second row of buttons, it’s time to fill the buttons with options. Place this code into your functions.php file:

Now you need to make sure these styles are available in your CSS file. Add this CSS code to your theme’s stylesheet and editor-style.css file.

If you don’t have an editor-style.css file, use the following code to create one. Place this code in your theme’s root directory and then add this code in your theme’s functions.php file.

You’ve now added your very own styles to your visual editor and you can access them quickly through drop down buttons. Of course, you can change the colors to anything you like, too.

Wrapping Up

There are a lot of fine choices for sprucing up your WordPress editor, and practically all of them are free. One thing’s for sure: they give you some simple functions that will make your posts shine brighter than the standard WordPress editor can. At least without spending a lot of time to get good results!

Have you done any mods to your WordPress editor? Did you use code, plugins, or both? Have you used these or any plugins that I didn’t mention? Let us know in the comments below.

http://premium.wpmudev.org/blog/customizing-wordpress-post-editor/feed/ 6