WPMU DEV's Blog - Everything WordPressWordPress 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 Sat, 25 Oct 2014 12:00:24 +0000 en-US hourly 1 http://wordpress.org/?v=3.9.2 Customizing the WordPress Comment Form http://premium.wpmudev.org/blog/customizing-wordpress-comment-form/ http://premium.wpmudev.org/blog/customizing-wordpress-comment-form/#comments Sat, 25 Oct 2014 12:00:24 +0000 http://premium.wpmudev.org/blog/?p=133401 The comment form is a great tool – it allows your readers to interact with your authors and vice versa. Engagement is extremely important for any website, such a direct line of communication should be fostered with care.

In this article we’ll take a look at some of the options we have for bending the comment form to our will.

Customize WordPress Comments Form
Customizing the comment form is easy!

The Comment Form Function

WordPress has a single function for outputting the contact form: comment_form(). It accepts a (rather lengthy) array as its first argument, which allows you to specify everything from the labels to the notice below the comment box.

It is most commonly called from the comments.php template file. In Twenty Fourteen and other default WordPress themes this is the favoured approach and I suggest you do the same.

comments.php itself is usually called from the single post template, single.php. It is called via the comments_template() function, take a look at the default themes to follow along.

Customizing The Form

There are three basic things we can do to customize our comment form. We can add our own styling, we can modify the arguments passed to the generating function to alter its behaviour or we can use plugins. We’ll mostly be focusing on the first two here.

Styling The Form

There are two approaches you can take. If you’re building a theme from scratch you can just add the necessary CSS to your existing stylesheet. If you would like to modify an existing theme you really should create a child theme.

How you style your comment form is of course up to you. However, since forms are generated using the same function their HTML output is roughly the same. Using the arguments we will discuss shortly you may add and remove elements but other then that, the classes and IDs are usually the same. Here’s how the HTML for the default comment form in Twenty Fourteen looks:

Customizing The Form Function

The comment_form() function takes two parameters. The first is an array where you can customize it, the second is an optional post ID. This can be used to output a comment form for an arbitrary post:

Let’s dig deeper and take a look at all the parameters we can use to modify the behaviour of our form:

Element IDs

Two parameters allow us to overwrite the default ID for the form and the submit button. id_form controls the ID for the form itself while id_submit determines the ID for the “submit” button.

Labels & Titles

Four functions allow us to control some of the labels and titles in the form. title_reply controls the title at the top of the form when writing a top-level comment. title_reply_to controls the title of the comment comment form when writing a reply to another comment.

You can control the text of the cancel reply link using cancel_reply_link and you can modify the text in the submit button using the label_submit parameter.

Notes & Text

There are four larger blocks of text available in the contact form. comment_notes_before and comment_notes_after controls the text seen before and after the comment form. Many people prefer to hide the notice about the usable HTML elements, and just set comment_notes_after to an empty string.

The text in the login notification can be controlled using the must_log_in and logged_in_as parameters. The former is used when a user comments without logging in, the later is displayed for logged in users.

Field Customization

Fields can be customized by specifying their full HTML. Oddly enough the author, email and url fields can be customized by using the fields parameter while comment field has it’s own parameter: comment_field. Take a look at the example below which shows the default code for each field.

Using Plugins

There are a number of plugins which modify comments. Some add functionality like AJAX to prevent page reloading, some add styling and some replace the default comment form with a third-party solution like Disqus or Facebook comments.

Take a look at the comments related plugins available in the repository, at the time of writing there are 1,533.


Hopefully you have a better picture of the possibilities the comment_form() function offers. While this is not a perfect implementation from WordPress by any measure, it is flexible enough to allow for many modifications.

If you have any great tips on handling comment forms or perhaps you’ve written your own comment form, let us know in the comments below.

Image credit: Sergey Zolkin, icons made by Yannick from www.flaticon.com is licensed by CC BY 3.0

http://premium.wpmudev.org/blog/customizing-wordpress-comment-form/feed/ 0
How to Create WordPress Custom Post Types http://premium.wpmudev.org/blog/create-wordpress-custom-post-types/ http://premium.wpmudev.org/blog/create-wordpress-custom-post-types/#comments Wed, 22 Oct 2014 12:00:00 +0000 http://premium.wpmudev.org/blog/?p=133085 The custom post type feature is what transforms WordPress from a blogging platform to a fully-fledged content management system.

Post types cannot be created and managed from the admin but can be exposed very easily using a little code.

In this article, I’ll show you how to create a custom post type for recipes and take you from the very basics to some more complex cases. Let’s begin.

Custom post types
Create your own custom post type.

What Is A Post?

Before getting into custom post types I think we should clarify some terminology since the naming convention results in a bit of confusion.

It is best to think of a post as a unit of content stored in the database. Each post has a post_type property, which defines what type of content it is. Here’s where things get tricky. One of the most commonly used built-in post types is named “post.”

This means that “post” can refer to any post entered into WordPress (whether this is a blog post, a page or a custom type), but it can also refer to a regular ol’ blog post.

For the purposes of this article I will be using “post” in its general meaning of an entry in the database. When talking about posts with a post type of post I will use the “blog post” convention.

Custom Post Types

In essence, a custom post type is nothing more than a change in the post_type attribute of a post. If you publish a blog post on your website and go into the database to rewrite the post type from “post” to “page” the post will now show up in the pages section in the admin.

WordPress defines a bunch of properties for each post type. Is the particular post type searchable? Is it visible in the admin? Can categories and tags be assigned to it, does it allow comments? A number of these features can be set for each custom post type.

So what is a good example of a custom post type? Let’s assume you love food and cooking. Chances are you have a website where you write about your personal things, but now and then you publish a recipe. A recipe is a very different type of content than a personal blog entry. In this case it may be appropriate to create a “recipe” post type.

Recipes post type
A newly created recipes post type.

When To Use Custom Post Types

It may be difficult to figure out when a custom post type is needed. Sometimes you can get by with categories. In our previous example we could have created a “Recipes” category.

So where’s the line? When should we use categories and when are custom post types more appropriate?

There really isn’t a set-in-stone rule here. It comes down to practicality, personal preference and how your theme is built. There are some good guidelines though; if it seems like some of these apply to you, a custom post type might be in order:

  • If you publish at least two very different types of content. For example, personal blog entries and recipes.
  • If it would be better to visually and structurally distinguish a specific type of content. For example: personal blog and your illustration portfolio.
  • If a type of content doesn’t fit in a chronological order. For example, a company blog and company style guides.
  • If a content type could easily be separated out into a different website and still remain coherent. For example, a personal blog and sold products.
  • If using categories and tags would lead to over-complicated taxonomies. For example, a personal blog and movie reviews.

Built-In Post Types

Now that we understand a bit about custom post types, let’s take a look at the post types WordPress uses by default. Many people know about posts (post) and pages (page) but did you know that uploaded images are also posts? They use the attachment post type.

Surprisingly enough there are two more: revisions (revision) and navigation menus (nav_menu_item). Revisions are just like posts but they contain the data about past versions of posts. Navigation menu items hold information about each separate item in the navigation system.

Creating A Custom Post Type

Enough talk! Let’s actually create a custom post type. All the code in this article is best placed in a plugin. If you’d like to just give it a quick go you can place it in your theme’s functions file, but I advise moving it to a plugin for production use.

To create – and highly customize – a post type you would only need a single function: register_post_type(). The documentation for it is pretty hefty but allows for some great modifications. To register a very simple custom post type you’ll only need a couple of lines:

Let’s analyze the basics. Notice that register_post_type() is used in a function that is hooked to the init action. It takes two arguments: the custom post type and an arguments array. The custom post type should be 20 characters at most and must not contain any spaces or capital letters. I also recommend writing singular forms (post, page, recipe, book, etc.). We’ll be looking at the arguments in a detail soon.

Customizing Post Types

There are three main things you can do to customize your post types:

  • Modify the arguments of the register_post_type() function
  • Add custom interaction messages (post deleted, updated, etc.)
  • Adding help sections to various screens in the custom post type admin

Let’s take a look at the most common arguments you can change when you register the post type and then turn our attention to the interaction messages and help text.

Description and Labels

If you use the simple method of registering a post type you’ll notice that buttons still say things like “New Post” and “Delete Post”. These can be customized using the labels property of the argument array.

Note that in the previous example we used the label property, this example uses labels. Make sure to use translation functions if your work will be for public consumption.

Post Type Visibility

There are a number of parameters which allow you to fine-tune the visibility of your custom post type in the front and backend. The most prominent one is the public parameter, which sets the values of other properties in one go.

If it is set to true, the post type will be included in searches, the UI will be shown, it will show up in the admin bar and so on. This is similar to how built in pages and posts work.

If it is set to false, the post type is excluded from searches, it will not show up in the UI, it will be hidden in the menus and so on. This is like the built-in revision post type.

For more granular control you can specify properties separately. The value of all the parameters below is the same as the value of the public parameter, except for exclude_from_search. The value of this property is the opposite.

  • public
  • exclude_from_search
  • publicly_queryable
  • show_ui
  • show_in_nav_menus
  • show_in_admin_bar

This example creates a post type which holds our notes on customers. We probably don’t want this to be visible in any way on the front end so I’ve made sure the public property is false. We do want to be able to manage them in the backend so I’ve set the show_ui and show_in_admin_bar properties to “true.”

Menu Customization

You can use three functions to modify the behaviour of the menu entry for your custom post type. show_in_menu sets where the menu is shown. If set to false the menu entry is not shown. If set to true it will be shown as a top level menu. You can set it to an existing top level page like upload.php to add it as a sub-menu.

The menu_position property sets where the menu shows up in the top-level list. Take a look at the Codex for the numbers to use for specific placements.

Finally, the menu_icon parameter allows you to set an icon. You can add a URL to an icon, or you can use the name of an icon from Dashicons which now ships with WordPress.

The code above will add our post type as a top level menu entry into position 20 (which is just below pages) and It will use the carrot icon from the Dashicons set.

Configuring Post Type Features

You can choose a number of features to use or discard for your custom post type. The hierarchical property will create a flat structure (like posts) when set to false. If set to “true,” you will be able to create parent-child relationships like you can with pages.

The taxonomies property allows you to assign custom taxonomies to the post type. This is an array of taxonomy slugs. The following example creates a hierarchical post type with support for tags.

If you plan on using custom taxonomies you will still need to create the taxonomy with the register_taxonomy() function.

The supports property holds an array of features which the post type supports. These have an effect on the admin user interface and on some parts of the front end as well. Here’s a list of available options:

  • title
  • editor
  • author
  • thumbnail
  • excerpt
  • trackbacks
  • custom-fields
  • comments
  • revisions
  • page-attributes
  • post-formats

Archives And Rewrites

has_archive is a great property which allows you to create a listing of your post type on the front end automatically. By setting the value to true you’ll find a list of your custom posts at http://yourdomain.com/post_type/. In your theme you can customize this listing using the archive-posttype.php file.

A full guide to rewrites is a bit out of the scope of this article, but it’s handy to know about them. The rewrite property defines how post type URLs should be handled. A good use-case is if you are creating a post type for a common task, say products. To make sure your plugin doesn’t conflict you could use “my_product” as the post type and rewrite it to “product” in the URL. Here’s how:

Post Type Interaction Messages

Whenever you perform an action on a post (saving, deleting, searching, etc.) you receive messages which give you feedback about your action. These messages can be tailored to the post type using the post_updated_messages filter, here’s how:

First of all, note that the $messages variable passed to the function contains all messages. The sub-arrays contain the messages for specific post types. All we need to do is define an array for the custom post type with the appropriate messages. Don’t forget to use translation functions on those messages. I’ve left them out here for brevity’s sake.

Contextual Help

Ever noticed the help tab in your posts or pages section? If you click there you’ll see that you can add a great little help section split into tabs. Adding contextual help is extremely important as it allows users to get help on the spot. This is better for them and better for you as well – the fewer support requests you get, the better.

We’ll need to use the $screen object in the function we hook to admin_head. The template for adding help sections is quite straightforward. Here we go:

The first thing we do is check the current screen. If we are not on the main post type screen we return early. If we are on the correct screen we can create our help tabs. Each help tab consists of a unique ID, a unique name and the content of the tab. These can then be registered individually with the add_help_tab() method.

Putting It All Together

The code to register a recipe post type, along with interaction messages and help sections would look something like the example below. Don’t forget the settings you use are ultimately up to what your project requires.


By now you should know what a post type is, how to create one customized to your needs and how to add messages and a help section to it.

It takes some practice to know when to use post types, when to use taxonomies and – more importantly – when not to use them. The only way to learn is by doing, so go and experiment.

If you have any great tips and tricks about custom post type or some great ways you’ve used them, please share in the comments below.

Image credit: Icon made by Freepik from www.flaticon.com is licensed under CC BY 3.0.

http://premium.wpmudev.org/blog/create-wordpress-custom-post-types/feed/ 6
Why You Shouldn’t Use functions.php (And What You Should Do Instead) http://premium.wpmudev.org/blog/why-you-shouldnt-use-functions-php/ http://premium.wpmudev.org/blog/why-you-shouldnt-use-functions-php/#comments Tue, 21 Oct 2014 14:30:00 +0000 http://premium.wpmudev.org/blog/?p=133167 I believe people who use WordPress can be separated into three broad camps:

  1. Plug and players: WordPress enthusiasts who are probably not experienced website designers and are looking for a turnkey solution. They will find a theme, install it, and probably get on with content creation.
  2. Tweakers: These folks will take a theme that could probably be used straight out of the box and apply their own tweaks. They will probably use the custom.css and custom_functions.php files (or similar) to customize their theme. They will take an off the shelf option and mess around with it until they have something that (a) suits their needs, and (b) looks unique.
  3. Frameworkers: These are usually developers who will start off with a theme framework that offers very little beyond – you guessed it – a framework, upon which content can sit. Hours or days later, they will have crafted crafted something truly unique and customized to their – or their client’s ≠ specific needs.

If I had to guess, I would say the biggest camp out of the three is the tweakers.

And let’s face it: WordPress is a tweaker’s paradise. Armed with nothing more than Google search and your functions.php file, wordPress makes it easy to add diverse functionality to your website with relative ease.

The only problem is many tweakers are playing with fire. Using functions.php to add functionality to your site can be an accident waiting to happen (for multiple reasons). In this article I will explain why, and offer you a far better alternative.

Add functionality to your WordPress site, but not with your functions.php file.

How WordPress Works

At the core of WordPress lies a simple principle: design and functionality should (whenever possible) be clearly separated.

That is why we have themes and plugins; ostensibly, themes are solely responsible for design and plugins are solely responsible for functionality. One should be able to switch themes without affecting functionality, and one should be able to deactivate plugins without affecting design.

This isn’t always possible (some of the reasons for which I’ll get onto shortly), but the separation of design and functionality is an ideal that any WordPress developer worth his or her salt should aim for.

So Where Does functions.php Fit Into This?

functions.php is a theme-specific file, by which I mean it exists in a WordPress theme’s directory and pertains only to that theme.

As you might guess from the name, functions.php contains functions that are relevant to the theme, examples of which are:

  • Use of featured images
  • Length of excerpts
  • Widgetized areas

These types of functions are exceptions that prove WordPress’ design/functionality separation rule. While they are elements of functionality, they are relevant only to their parent theme, and may not be appropriate when applied to another theme. As such, they belong in functions.php and should remain there.

For example, an excerpt length of 200 words might look fantastic on one theme but terrible on another. Although we are technically playing around with the “functionality” of a site by adjusting the excerpt length, including the necessary code in functions.php is the right thing to do.

I don’t intend to get into the complexities of effectively utilizing functions.php in this article, but it is worth mentioning at this time that if you’re going to include a lot of theme-specific functionality in your site, you should consider creating an inc directory within your theme (or using a pre-existing directory if it already exists) to effect some organization amongst your theme’s functions. Here’s a great read from WordPress developer Tom McFarlin on the subject if you want to go further down that path.

My ultimate point is this: functions.php is not the enemy. It is a valuable cog in a theme’s engine; necessary for all but the most basic of designs.

However, the misuse of functions.php is rife and should be stopped.

When You Shouldn’t Use functions.php

The simple answer to when you should use functions.php is “almost never.”

The slightly more complicated answer is “use your noggin.”

If you understand what functions.php is for (functionality strictly related to a particular theme), you should be able to figure out what it isn’t for.

Easy examples can be found within your WordPress website’s plugins directory. Plugins are (ideally speaking) logically arranged “packets” of code separated by their intended functionality.

One of the best (and higher profile) examples of the whole point of separating functionality from design in WordPress is Google Analytics tracking code, which looks like this:

Google Analytics tracking code
This code needs to be added into the head section of your site in order for visits to be tracked.

You have three main options when it comes to adding this code:

  1. Add it manually to your theme’s header.php file
  2. Add it manually to your functions.php (using a hook)
  3. Use a plugin

If you use options one or two, your tracking code will disappear if you change themes and visitors will no longer be counted by Google. (It may also disappear the next time your theme is updated.) But if you use option three (my recommendation is Google Analytics by Yoast), you’re golden. Unless you have a senior moment and deactivate the plugin you’re using, that tracking code is going nowhere.

My simple advise is this: If in doubt, use a plugin. They’re popular for a reason.

Why You Shouldn’t Use functions.php

In explaining the “when” above, I have also gone a fair way in explaining the “why:” Don’t use functions.php because changing your theme will change the functionality of your site, which is all kinds of wrong.

However, there are a couple of other major points I should make to further strengthen the reasons for avoiding functions.php as much as possible.

First of all, there is the dreaded “white screen of death.” Quite frankly, if you’ve never encountered this while messing around with WordPress, you haven’t lived. Or at least you were far more careful than me when you first started tinkering with WordPress.

I feel at this stage we need a screenshot to clarify what this white screen of death actually looks like:

White screen of death

Scary. But what does it mean?

Well, to put it in the Queen’s English, one encounters the white screen of death when one cocks up one’s PHP.

In other words, you’ve screwed up.

To put it another way, syntax errors in PHP code inserted into functions.php can “break” your site, leading to you seeing nothing more than a white screen. (Don’t ask me where the “death” comes into it. As far as I’m aware, nobody gets hurt.)

Upon encountering the white screen of death, it’s better if you were editing your site via FTP or an online IDE (like ShiftEdit) rather than the WordPress backend, otherwise you’ll have some trouble getting back into your site. Plus, you’ll get a slap on the wrist from me for using the WordPress backend. Naughty.

But I digress. The point I’m getting to is this: placing your PHP code into a plugin can prevent the white screen of death from ever happening. Instead, WordPress may be able to deactivate the offending plugin without negatively affecting the continuing operation of the site as a whole.

Secondly, using functions.php is just plain messy if you plan on inserting more than a handful of code; especially if the theme you’re using already has existing functions.

Thirdly, and as I have already mentioned above, code in functions.php is theme-specific (i.e. will not travel when you change themes) and can be overwritten by theme updates.

None of this is good, and should convince you that functions.php is not the place you want to place your code in the majority of cases. Sure; leave whatever’s there by default as it is (on the assumption that the theme developer has included theme-specific functionality only), but any new code you’re adding is likely fair game.

So what do you do instead?

The Beautiful Alternative: Create Your Own Plugin

If you’re a garden variety WordPress tweaker and have never created your own plugin before, you’d be forgiven for thinking that it involves some kind of complicated and arcane process. Perhaps some kind of incantation is required.

Fortunately, that’s not the case. If you know how to edit a functions.php file properly (via FTP or an online IDE), you already have the necessary skills to create a plugin for your all of the code you would otherwise be putting into functions.php.

So let’s do it.

Firstly, navigate to your WordPress website’s root folder via FTP (or your hosting panel’s file manager, or via an online IDE). From there, you should navigate to wp-content/plugins:

WordPress Directory

The folders you see within the plugins directory are (as you may imagine) the plugins currently installed on your site. To create your own plugin, just create a new folder. I’m going to name it tme-custom-functions:

Plugins list

(“TME” are my initials, and I’m prepending them to the plugin name so that I don’t accidentally use an existing plugin’s name.)

Next, create a PHP file with the same name within your plugin’s folder:

Custom Functions plugin

Finally, insert the following code into your brand new PHP file:


* Plugin Name: Custom Functions Plugin
* Description: This plugin contains all of my awesome custom functions.
* Author: Tom Ewer
* Version: 0.1

/* Your code goes below here. */

/* Your code goes above here. */


That’s all there is to it! Make sure your file is saved and the plugin will now appear within your WordPress plugins list:

Plugins List

Of course, your plugin doesn’t do anything yet, but you are now free to insert any custom functions that previously resided in your functions.php file, and they will continue to work as normal.

Going a Step Further: Creating a “Must Use” Plugin

The average plugin is all well and good, but what if you want your chosen functions to work on your site under all circumstances? What if you don’t want your new custom plugin cluttering up your plugins list?

It sounds like you need to make it a “must use” plugin, which are plugins that are always active on your site (and cannot be deactivated). They won’t even appear on the plugins list in WordPress unless you click on the Must-Use link within the plugins list.

To make your plugin “must use,” simply create a folder named mu-plugins within your WordPress site’s wp-content directory, then move your plugin’s PHP file (not the whole folder) into it.

Hey presto! The plugin disappears from your list and reappears within a new Must-Use section:

Must Use

Wrapping Up

You now know when you should use functions.php and when you should create your own plugin.

You also know that it is almost always worth creating your own plugin for a number of reasons. Now you too can feel like a brainy WordPress developer by creating something that appears on the WordPress backend! Don’t pretend that it doesn’t make you feel far better at coding than you actually are (at least, that’s how it makes me feel).

If you have any questions or concerns about anything I’ve discussed in this article, please fire away in the comments section below and I’ll get back to you!

Photo Credit: skoop.

http://premium.wpmudev.org/blog/why-you-shouldnt-use-functions-php/feed/ 22
Add Twitter Cards to Your WordPress Website and Boost Your Social Shares http://premium.wpmudev.org/blog/twitter-cards-wordpress/ http://premium.wpmudev.org/blog/twitter-cards-wordpress/#comments Mon, 20 Oct 2014 12:00:12 +0000 http://premium.wpmudev.org/blog/?p=133169 Have you noticed how some tweets include additional content, such as large images, a collection of smaller images, and even sometimes embedded video or audio files?

In most cases, this is achieved by using Twitter’s Card feature. It’s a great way to make your content really stand out from the crowd when it is shared on this popular social network. The great thing about Twitter Cards is that when they are shared, there is a greater potential for your content to catch the attention of other users and increase traffic back to your website.

In this article I’ll explore the different types of Twitter Cards available and how you can enable and start using them on your WordPress website.

Twitter player card
An example of a Twitter Player Card.

What are Twitter Cards?

Twitter Cards allow you to attach additional content to the tweets in which your posts are shared. This content can be defined on your website and then each time your posts are shared on Twitter, it will be included in the tweet.

As this Twitter Card content can include photos, video, product information, and more, it allows you to produce some eye-catching tweets that will make your content stand out in the Twitter streams of your followers.

An example Twitter Photo Card
The Twitter Photo Card.

The great thing about using Twitter Cards with WordPress is that you only have to enable them once and then each time your posts are shared on Twitter you can reap the rewards of having content that really stand out from the crowd.

For a little work up front, you can experience increased social media shares and more clicks back to your website each time your posts are shared by you or your visitors.

An example Twitter Product Card
The Twitter Product Card

There are currently seven Twitter Cards available:

  • Summary Card: Title, description, thumbnail, and author username.
  • Summary Card with Large Image: As above but with larger featured image.
  • Photo Card: Photo-only Card.
  • Gallery Card: A collection of four photos.
  • App Card: For promoting a mobile app with direct download link.
  • Player Card: Includes video or audio media player.
  • Product Card: Contains product information and direct link to that product.

As you can see, whatever type of website you run there is a good chance there is a card that can help promote your content better on Twitter.

How to Enable Twitter Cards

It would be great if Twitter would crawl each URL that is shared on its network and then use any additional information from the shared content to create the Twitter Card automatically. However, this isn’t the case and you will have to do a little work to enable them for your website.

This is a good thing though as anyone who are willing to put in some extra effort up front will be able to gain an advantage over other websites by ensuring their tweeted content stands out from the crowd.

The process for enabling Twitter Cards for your website involves two main steps:

  • Adding the necessary code to each post that you want to enable Twitter Cards for, and
  • Requesting approval from Twitter to enable cards.

Twitter has published a helpful getting started guide to using their cards. However, as usual WordPress users have it easy thanks to some free and easy to use plugins that take care of all this for you.

The Best Twitter Card Plugins for WordPress

While there is a great free plugin that is dedicated to enabling Twitter Cards in WordPress, there are also two WordPress plugins you might already be using on your website that allow you to enable Twitter Cards: WordPress SEO by Yoast and Jetpack.

WordPress SEO by Yoast

This popular and free SEO plugin also includes basic support for Twitter Cards amongst its list of features. If you are using this plugin and don’t want to install a dedicated Twitter Card plugin, then navigate to the Social sub-menu item and switch to the Twitter tab.

WordPress SEO plugin settings
WordPress SEO plugin social settings

From here you can enable Twitter Card meta data, which adds the necessary code to your website. Then enter your Twitter username, which will be included when your content is shared, and also set the default Twitter Card type to use.

Unfortunately, with the WordPress SEO plugin there are only two out of seven Twitter Card types to choose from: summary and summary with large image. However, if these are the only cards you are interested in using then this plugin could suffice.

Request Twitter Card Approval
Request Twitter Card usage approval for your site

The final step is to then enable Twitter Cards for your website. This only needs to be done once per website and can be completed from the Twitter Card validator page by entering the URL of your website and clicking on the “Request Approval” button and entering the required information.

Approval Email
Approval Email from Twitter

Shortly after submitting your approval you will receive a confirmation email notifying you that the Twitter Card you are planning to use on your website has been activated. If you want to use other Twitter Card types on your website, you will need to enable them on your site and then make another request through the Twitter Card validator page.

After the Card has been enabled for your website you should then be able to preview a post on your website and using the validator. This will enable you to see how your content will look when it is shared by you or anyone else on Twitter.

Twitter Card Preview
Use the Twitter tool to preview your Card

JM Twitter Cards Plugin

The JM Twitter Cards plugin

If you don’t mind installing another plugin on your website, or you aren’t already using a plugin that supports Twitter Cards such as WordPress SEO or Jetpack, then JM Twitter Cards is a great free choice.

The main benefit of using this plugin is that it includes support for more Twitter Card types while also allowing you to choose a specific Card type for each individual post. Other features of the plugin include:

  • Specify an image to be displayed in the Tweet.
  • Preview your card on the post editor page.
  • Support for multi-authored content.
  • Add author’s Twitter username and site’s Twitter username to tweets.
  • Set a fallback image to be used by your posts that don’t contain an image.
  • Define the image sizes to be used in the cards.
  • Add app information for the Twitter App Card.
  • Detailed user documentation.
  • Enable Twitter analytics to track tweets.

There is also a very helpful video tutorial that accompanies the plugin to help you get started with Twitter Cards as quickly as possible.

JM Twitter Cards is compatible with the WordPress SEO plugin so you can use them together without any conflicts, despite some overlap between the two tools.

Once this plugin is installed on your website the site-wide settings can be configured under the plugin dashboard found under the “JM Twitter Cards” menu item on your admin sidebar.

JM Twitter Cards Settings
JM Twitter Cards plugin settings

If you chose to display the meta box through the site-wide settings you can then define how each individual post will look when it is shared on Twitter. This is recommended as it gives you a lot more control over how your Twitter Cards will look.

JM Twitter Cards Post Meta

By using the Twitter Cards meta box you can choose a card type for the post you are working on and also set another source for the card image by entering a URL or uploading a file.

JM Twitter Cards Post Meta

By displaying the plugin meta box on the post editor you also get a basic preview of how your content will look when it is shared on Twitter.

JM Twitter Cards Preview
A preview of the Twitter Card from the post editor.

As you can see, the JM Twitter Card plugin allows you to include two Twitter usernames in the card: one which belongs to the post author and one for the website.

Once you’ve configured the plugin you must also request for cards to be activated for your website. This can be done through the Card validator page and once you’ve received the approval email from Twitter, you can start using this plugin to add additional whenever your content gets Tweeted.


As you can see, it doesn’t take much effort to enable Twitter Cards on your WordPress website to help make your content really stand out when it is tweeted. You can either take a set-it-and-forget-it approach or customise each individual post for maximum effect; adding a custom image and description as well as choosing the best card type for each piece of content.

Whichever plugin you use, remember you will need to get an approval from Twitter to enable cards for your website and then also enable each additional individual card type you would like to make use of. It’s also a very good idea to add social sharing buttons to your posts using a suitable plugin so that your readers can easily tweet your content to their followers.

While the functionality of the WordPress SEO and Jetpack plugins do allow you to use Twitter Cards on your website, if you want more control over how your content looks when it is shared then using a dedicated plugin such as JM Twitter Cards is highly recommended.

If you want to break through the constraints of Twitter’s 140 character limit and draw more attention to your content then Twitter Cards are the way to go.

Do you use Twitter Cards? Do you think they’re worth using on your WordPress site? Let us know in the comments below.

http://premium.wpmudev.org/blog/twitter-cards-wordpress/feed/ 3
How to Hide the WordPress Update Notification To All But Admins http://premium.wpmudev.org/blog/hide-the-wordpress-update-notification/ http://premium.wpmudev.org/blog/hide-the-wordpress-update-notification/#comments Sun, 19 Oct 2014 12:00:00 +0000 http://premium.wpmudev.org/blog/?p=133381 One of the great things about WordPress as an open source project is that the core code is regularly updated with improvements and security patches.

Major releases, along with minor security releases, of WordPress are usually shipped two or three times a year. If you have automatic updates turned on, your WordPress install will be updated each time there’s a minor release. However, you will need to manually update your software for major releases.

Whenever there’s a major release available, a notification will display at the top of your admin area, letting you know your version is out-of-date and you need to update the core code.

For many people, this nag can be annoying. And if you developer websites for clients, you may want to hide it. After all, who wants to let their clients know their software is old?

In today’s Weekend WordPress Project, I’ll show you how to easily hide the update notifications.

Update notification
Find out how to hide the update notification.

It’s Important to Update WordPress

Whenever there’s a new release, it’s highly recommended that you update your version of WordPress as soon as possible, so you are always running the latest security updates.

The only problem is, if you’re updating a live site you don’t know what effect the updated core code may have on your site. With each release of WordPress, the core team work on improving the code, which means old functions can be removed.

If you have themes or plugins that use deprecated functions, upgrading WordPress can break your site. This is why it’s a good idea to have a development site that mirrors your live site where you can test new WordPress releases.

The WordPress update notification is shown to all users who log into the backend, but the message is different depending on your role. Only admins are able to update the core code. Other users will get a message which says a new version of WordPress is available and to contact the site admin.

Notify admin
The backend of WordPress for subscribers.

Hiding the Update Notification

Developer Paul Underwood has a handy snippet for hiding the notification. Simply add the following code to your functions.php, or use it to create a new plugin:

function hide_update_notice_to_all_but_admin_users()
    if (!current_user_can('update_core')) {
        remove_action( 'admin_notices', 'update_nag', 3 );
add_action( 'admin_head', 'hide_update_notice_to_all_but_admin_users', 1 );

Next time subscribers log in, WordPress will no longer display the update nag:

No nag
The update notification has magically disappeared!

The notification will continue to display for admins, so you’ll always know when there’s a new version of WordPress available to download.

Admin update
Admins will still new when newer versions of WordPress are available.


http://premium.wpmudev.org/blog/hide-the-wordpress-update-notification/feed/ 6
The Dreaded WordPress Connection and Data Not Received Errors: How to Fix Them http://premium.wpmudev.org/blog/wordpress-connection-data-not-received-errors/ http://premium.wpmudev.org/blog/wordpress-connection-data-not-received-errors/#comments Sat, 18 Oct 2014 12:00:00 +0000 http://premium.wpmudev.org/blog/?p=132894 If you’re one of many people who have experienced intermittent outages of your WordPress site, this article is for you.

It might seem hopeless right now, but if you’ve experienced any one of these errors, there is a solution:

  • “Data not received” in the Google Chrome browser
  • “Connection error” in the FireFox and Internet Explorer browsers

You’ve checked your internet connection and everything works; you’re able to access other major website such as Google, and Twitter; you’ve double checked with your hosting company, and you haven’t exceeded your storage, memory, or bandwidth, but you’re still noticing these errors.

If this sounds all too familiar, here are the steps to determine what the issue is, followed by the necessary troubleshooting, and how to fix it.

Connection error
Stop connection errors and data not received messages in their tracks.

When Your Site is Down, it Says a Lot About You

Okay, you caught me! Your site’s outages won’t say anything about you, but they sure say a ton about the probable cause.

Here are a few things to consider before going ahead and troubleshooting the issue.

What Kind of Hosting are You Using?

If your site is housed using shared or VPS (Virtual Private Server) hosting, and you experience short bursts of intermittent outages, then the likely cause could be that the server you are on is overloaded. This can especially be an issue if your website is awesome and has more than a few plugins and pages. It might be time to consider upgrading or switching hosting companies.

In either case, it’s a good idea to call your iInternet service provider and ask them to white list your hosting IP address. While you’re on a roll, call your hosting company and ask them to do the same for your external IP address, given to you by your ISP. This isn’t likely the issue and, in my experience, you may be faced with both companies letting you know that they do not block any IP address; however, it will help you eliminate this as the possible cause of the error messages.

If you’re using dedicated hosting, then your issue is likely not with your server, given that you have not exceeded your allotted limits. It’s time to go ahead and start troubleshooting.

Let’s Start Troubleshooting

For Windows

Fire up the command prompt:

  1. Press the Windows key and “R” at the same time.
  2. Type “cmd” into the box, and click “OK”.

Here’s the list of steps you want to take after the command prompt has opened:

  1. Type “ipconfig /all” (without the quotation marks) and press enter.
  2. When that’s complete and the command line comes back up, type in “ping google.com”, then press enter.
  3. When completed, follow it up with your domain that has the issues by typing “ping example.com” (type in your domain in place of the example, of course), then press enter.
  4. Right click inside the window and click “Select all.”
  5. Press “Ctrl” and “C” to copy the information.
  6. Paste this in a word processor.
The Windows command prompt after the ipconfig /all prompt
This is what the Windows command prompt window will look like after running the “ipconfig /all” command. Keep in mind, yours will not look exactly the same, but very similar.

For Mac OS X

Fire up a new Terminal window. Here’s the list of steps you want to take after the command prompt has opened:

  1. Type “ifconfig -a” (without the quotation marks) and press return.
  2. When that’s complete and the command line comes back up, type in “ping google.com”, then press return.
  3. After about 15 seconds, stop the ping by pressing Ctrl and “C.”
  4. When completed, follow it up with your domain that has the issues by typing “ping example.com” (type in your domain in place of the example, of course), then press return.
  5. After about 15 seconds, stop the ping by pressing Ctrl and “C.”
  6. Select all the information by pressing , shift, and the up arrow.
  7. Copy everything by pressing  and “C.”
  8. Paste this into a word processor.
The ifconfig -a in terminal, on a mac OS
This is an example of what the “ifconfig -a” command generally renders in terminal on a mac OS. All that’s left is to ping google.com and your website.

You’re Almost Done! The Final Steps

Close the command prompt or terminal and head over to OpenDNS to change your settings to match the nameservers they provide. They ensure zero downtime, so if your website works perfectly using these new settings, then it’s much easier to isolate the problem.

Once at their setup page, you can follow their instructions to setup the new nameservers on your computer. Then follow the same troubleshooting steps we just went through. Send all this information first to your hosting company, and let them know you’re experiencing intermittent outages, and you’ve included some troubleshooting information for them to review. It’s likely that this isn’t a tier-one support issue, and you may need to relay this information to a senior technician.

If you have migrated your site lately, confirm the last date your site was moved with your hosting company. If it has been at least two days, then you can go ahead and send this information to them. Make sure to keep a note of this date for your records.

If they are unable to resolve this issue for you, then send this information to your ISP, and explain what you are experiencing. You may be experiencing a third party DNS issue if other people also have troubles accessing your site. In this case, the issue does not have to do with your ISP, but you can ask them to be your advocate to help resolve this issue for you. You probably won’t have to contact your ISP anyway, as your hosting company will be able to solve this problem for you in most cases.

You’ve probably noticed at this point that there’s not a whole lot you can do other then troubleshooting, and that’s because in most cases, the issue isn’t your computer or your internet connection, but rather a DNS propagation issue that needs to be looked at and resolved by your hosting company, or your ISP.

With these steps, you’ll be three quarters of the way to planning your next, much-needed vacation!

Image credit: jjflash53.

http://premium.wpmudev.org/blog/wordpress-connection-data-not-received-errors/feed/ 0
White Labeling Your WordPress Site: The Complete Guide http://premium.wpmudev.org/blog/white-labeling-wordpress/ http://premium.wpmudev.org/blog/white-labeling-wordpress/#comments Fri, 17 Oct 2014 12:00:00 +0000 http://premium.wpmudev.org/blog/?p=133034 When you build a website, one of your top priorities should always be to put your personal stamp on the project. You can do this through your visual style choices, your custom graphics, or even custom footers that say—in essence—I made this.

And while many developers focus on adding branding to the frontend of a site, the backend is often left untouched without a hint of customization. That can be fine if you’re the only one working on the site but if you have a team or allow client access, the generic out-of-the-box WordPress dashboard might not serve you all that well.

Basically, your site’s backend could be doing more for you. It could be working harder for you. And that’s why white labeling—the process of adding personalized, branded touches—is such a good idea. So today I’m going to present some solutions for white labeling your site, from plugins and themes that guide your customizations to manual code snippets you can drop into your site right this second.

White label WordPress
White label your WordPress site.

What’s the Point of White Labeling?

White labeling is all about ensuring your site is fully branded. From the frontend to the backend, your site should reflect your business and the image you want to put out there in the world. Then again, your thoughts may fall more in line with the following:

“But you’re talking about customizing the part of my site the public never sees! What’s the point?!”

Sound like you? If it does, that’s okay. I completely understand the impulse to focus on the part of your site your potential clients and customers will see. Believe me. I get it. But sometimes doing a little extra work to make the internal operations surrounding your site more streamlined, more effective, and more personalized can have a dramatic impact on that aforementioned outward appearance.

Here are a few things white labeling will definitely do for you:

1. Reduce Confusion for Clients

Sometimes, you’ll come across a client who has never heard of WordPress before and honestly doesn’t care that you’re using it. So seeing notes all over the place in the dashboard about WordPress-this and WordPress-that can be a bit confusing.

It would make a lot more sense to these folks if the footer of your dashboard noted that the site was designed by you wouldn’t it? Because I mean, you don’t want to receive an email at 2 a.m. from a client asking, “Who’s this WordPress outfit? I didn’t sign up for that!”

2. Increase Professionalism

At its heart, white labeling is about branding. As I said earlier, it’s about making your mark. A solid brand reputation stands to be perceived as more professional and more put-together than one that’s a bit all over the place.

You go to great lengths to customize other aspects of your sites, right? You wouldn’t even think of launching a site without a company logo. So why not have the same mentality for the backend? Team members and clients tasked with logging into your site for the first time are sure to be impressed when they see your logo and welcome message rather than the same generic WordPress ones they’d see on any other site.

3. Offer Additional Support

I think one of the coolest things you can do with white labeling is include links to additional documentation and support in the dashboard. This is so incredibly helpful to your clients and your team members who maybe aren’t as familiar with this whole WordPress thing as you are.

You can even link to support videos if you want to provide even further guidance.

4. Customize the Dashboard to Suit Specific Needs

The WordPress dashboard comes equipped with some things standard. But depending on your team or your clients, not every widget that appears there is going to be relevant. And again, for newbies, you only stand to confuse them if you present too much information at once.

White labeling affords you the opportunity to remove and/or add widgets to suit your needs at the time. For instance, if your team members are mostly contributors to your blog, they might only need to see the “At a Glance,” “Quick Draft,” and “Activity” widgets. Everything else would just be extra and possibly viewed as in the way.

Adding White Label Elements Manually

If you only want to add a couple of white label aspects to your site, it’s pretty easy to accomplish manually. Just a few code snippets can get you a custom login page or a custom greeting.

Here are a few ways you can white label WordPress. As always, make sure you backup your site before making any changes to the functions.php file:

Add Your Logo to the Login Page

WordPress Admin Login
This is a pretty familiar sight, isn’t it? And while it’s perfectly serviceable as a login page, it doesn’t do anything to remind the user that they’re visiting your site. Adding a custom logo here rather than the WordPress default one says, “You are on my site now!”

To change the logo you need to first create a custom image. You want something that’s going to fit nicely above the username and password fields. Between 300px and 315px wide, and 75px and 130px, tall ought to do it.

Save this image as a PNG file and upload it to your theme’s images folder.

Your next step is to insert a code snippet in your theme’s functions.php file. This one was written by Rick R. Duncan:


//* Do NOT include the opening php tag

//* Replace WordPress login logo with your own

add_action('login_head', 'b3m_custom_login_logo');

function b3m_custom_login_logo() {

    echo ''; }

Just make sure to swap out login.png with the name of your custom logo and adjust the height and width variables to match your image and you’ll be all set.

Duncan also suggests making this new logo link to your site’s homepage. I mean, why would you want to direct your clients to WordPress.org anyway? They’re doing business on your site! To make this change, you can add this bit of code to functions.php:


//* Do NOT include the opening php tag


//* Change the URL of the WordPress login logo

function b3m_url_login_logo(){

    return get_bloginfo( 'wpurl' );


add_filter('login_headerurl', 'b3m_url_login_logo');

That way when someone clicks on your logo, they will be taken to your homepage and not directed to WordPress.org, which could be very confusing for your client.

Change the WordPress Welcome Message

WordPress Howdy Welcome Message
“Howdy” can be changed to read whatever you’d like.

If the default “Howdy” just isn’t doing it for you, it’s possible to change the default message to something more your style or more in keeping with your brand. Just add this code snippet to your theme’s functions.php file and swap out the “Howdy” for your custom greeting:

add_filter('gettext', 'change_howdy', 10, 3);

function change_howdy($translated, $text, $domain) {

    if (!is_admin() || 'default' != $domain)
        return $translated;

    if (false !== strpos($translated, 'Howdy'))
        return str_replace('Howdy', 'Welcome', $translated);

    return $translated;

Change the Footer Text in the Dashboard

Here’s another prime spot to put your branding information. Instead of just letting the default “Thank you for creating with WordPress” ride in your dashboard’s footer, you can use a simple code modification to change this text to read whatever you want:

function change_footer_admin () {  

  echo 'Custom text goes here. Theme developed by &lt;a href=&quot;&lt;a href=&quot;&gt;http://www.linktowebsite.com&lt;/a&gt;&quot;&gt;Link to Website';  


add_filter('admin_footer_text', 'change_footer_admin');

Change the Dashboard Header Logo

Having a custom logo, footer, and welcome message are great, but if the logo in the admin header is still stuck on the default WordPress one, you’re going to create an inconsistent brand image.

According to Art of Blog, a good way to fix this is to use the following code snippet in functions.php:

function admin_css() {
echo '';


Then all you need to do is add a small bit of code to your admin.css file:

#header-logo {background-image: url(images/client_logo.jpg);}

Just make sure the image referenced here matches the file name of your custom logo and you’ll be all set.

Add a Custom Contact Widget to the Dashboard

When you first login to a WordPress site, you’re going to see something like this:

WordPress Dashboard Widgets
Most WordPress dashboards look something like this.

And while this view is likely fine for your internal team members, it might not always be ideal for clients who need more guidance or direction. Wouldn’t it be nice if you could direct clients back to your site in case they need help or would like to hire you for additional work? Well you can do just that by adding a contact widget. Rick R. Duncan has a code solution for this, too:


//* Do NOT include the opening php tag
//* Add theme info box into WordPress Dashboard

function b3m_add_dashboard_widgets() {

  wp_add_dashboard_widget('wp_dashboard_widget', 'Theme Details', 'b3m_theme_info');


add_action('wp_dashboard_setup', 'b3m_add_dashboard_widgets' );

function b3m_theme_info() {

  echo &quot;&lt;/pre&gt;
	&lt;li&gt;&lt;strong&gt;Developed By:&lt;/strong&gt;Your name&lt;/li&gt;
	&lt;li&gt;&lt;strong&gt;Website:&lt;/strong&gt; &lt;a href=&quot;http://www.websitelink.com&quot;&gt;Website name&lt;/a&gt;&lt;/li&gt;
	&lt;li&gt;&lt;strong&gt;Contact:&lt;/strong&gt; &lt;a href=&quot;mailto:youremailaddress@emailprovider.com&quot;&gt;youremailaddress@emailprovider.com&lt;/a&gt;&lt;/li&gt;


The end result looks something like this:

Custom Contact Dashboard Widget for WordPress
You can create widgets to display custom contact information.

As you can see, you can easily display your name, website, and contact information in its own widget.

You can also modify this bit of code to display links to your supporting documentation. So instead of showing your name and website, you may instead opt to display “For full support documentation visit: Site Name” or “Have any questions? Ask them on Your Forum Name,” and insert links as appropriate:

Custom Support Dashboard Widget for WordPress
Custom widgets can be used to display links to support docs, too.

Your clients shouldn’t have to guess at how to use your dashboard, so provide as much information as you can upfront and point them to as many of your custom resources as possible. Sure, there are plenty of tutorials out there about how to use WordPress, but why make a client search for that info when you can provide it under your own brand?

Change the Admin Color Scheme

The newest versions of WordPress offer the ability to change up how your dashboard’s color scheme looks. Still, these preset options might not be exactly what you’re looking for. Being able to customize the admin color scheme means you can ensure every aspect of your site’s backend matches your company’s branding.

To accomplish this, Smashing Magazine suggests creating a new CSS file. Call it admin.css and put it in your theme’s css folder. Make sure you use styles that work with WordPress. Then, open up functions.php and add this bit of code to call up that CSS file you made:

// Custom WordPress Admin Color Scheme

function admin_css() {

wp_enqueue_style( 'admin_css', get_template_directory_uri() . '/css/admin.css' );


add_action('admin_print_styles', 'admin_css' );

Plugins for White Labeling

If the thought of manually adding bits of code to white label every site you create is too much, a plugin-based solution may be just the thing you need. Here are a few that either do it all or do one thing really well:

Ultimate Branding


Of course we have to mention our own plugin, Ultimate Branding, first. We’re pretty fond of it and think it does a really great job of giving site owners the ability to add white labeling without having to dive into PHP.

This plugin makes it easy to add your brand to just about every aspect of the WordPress backend, including a custom login image, admin bar, global footer and dashboard footer content, meta widget, admin help content, custom multisite favicons, and much more. You can also remove dashboard widgets to ensure your clients are only presented with the information they absolutely need.

Ultimate Branding is an all-in-one plugin but far from a one-size-fits-all solution. Customization is the name of the game and when it comes to branding your site, thoroughness is key.

White Label Branding for WordPress


Another option for adding customization to your dashboard is to use the White Label Branding for WordPress plugin available on Code Canyon. While its primary focus is on letting you brand your site, it includes some other interesting features that are worth mentioning as well.

With the Dashboard Tool, you can add as many custom dashboard meta boxes as you want. Thanks to navigation options, you can hide top-level and sub-level menus, rearrange their order, hide individual menu items based on user role, rename menus, and change menu icons. You can even hide the admin bar altogether if you want to prevent users from poking around too far into your site’s settings.

It also offers a variety of color scheme options. For instance, you can add a custom color scheme for wp-admin, change menu and content area colors, and customize how buttons appear. The role and capability manager lets you establish custom user roles and capabilities, which you can then tie to some white label features. For instance, you may opt to have different users, based on their roles, see different dashboard metaboxes. So, admins and contributors wouldn’t see the same things, thus preventing confusion and potential for errors.

You can expect to pay $28 for a regular license and $140 for the extended license.

AG Custom Admin


Self-described as an “all-in-one tool for admin panel customization,” you can easily modify the admin bar and menu, add personal branding to the admin panel in the form of images and content, and swap out the colors used—including in backgrounds and text—to better suit your brand’s image.

With just a couple of clicks, you can change out the admin panel theme as well, change the dashboard widgets, and modify what appears in the Help and Screen options menus. The admin themes are responsive and perfectly suited for the admin panel and login page.

Tired of clients accidentally creating new pages instead of posts? You can hide the “New Page” option from the dashboard and prevent it from happening ever again. You can also hide the options to create new links, users, media, and posts should you so desire.

YouTube White Label Shortcode


Adding videos to your site can be a great way to incorporate media and dynamic content. However, just embedding YouTube videos using the standard embed code can look a bit out of place. The videos won’t necessarily blend in with the rest of your design and the formatting could be a bit wonky.

That’s why the YouTube White Label Shortcode plugin is so handy. Once installed, you can add any YouTube video you want but you have the option to change up the player’s logo, whether or not videos start immediately upon loading, the player style, and more.

While this short code generator is automatically added in a metabox on all post types, you can opt for it to only appear on the post types you specify.

Uber Login Logo


If you’re not big on all the white label features and just want to add your logo to the admin login page and call it a day, Uber Login Logo is a good way to accomplish that. With it, you can upload your logo via the standard media uploader and swap out the logo by adjusting a few settings. Simple.

It’s extremely lightweight, which makes sense since it only performs one function. Still, if you don’t feel like poking around in functions.php, this plugin will give you a branded login page without calling much attention to itself.

Disable WP Admin Bar Removal


If getting rid of the admin bar is your top priority on the white labeling front, you should check out Disable WP Admin Bar Removal. This plugin will let you select from several settings to remove the admin bar, the toolbar, and tooltips.

It can also hide admin icons on the backend of your site and can be used to add a header and footer log and a logout function at the top of the dashboard.

Admin Menu Editor


Changing the menus in your WordPress dashboard is another way to customize the backend experience for your team and clients. If you’d rather not poke around in code, Admin Menu Editor will get the job done quite nicely.

With it, you can change menu titles, URLs, icons, and CSS classes. You can also rearrange the order of menu items easily via a drag-and-drop interface and opt to hide or show any menu or menu item. It’s also possible to set who sees what version of your menu based on user capabilities and/or roles.

Another cool thing about this plugin is you can create custom menus that point to any section of your dashboard. Or, you can configure these menus to link to external sites. This can be an excellent way to incorporate links to your support documentation in the dashboard.

Admin Menu Editor Pro adds on a few extra features if you really want ultimate control over your menus. Some of these features include the ability to hide a menu from all but specific users, set per-role menu permissions, drag items between sub-menus and main-menus, and export the admin menu for use on other sites.

It’s available under three licenses—personal, freelancer, and business—which are priced at $19, $29, and $59, respectively.

Themes for White Labeling

Normally when a discussion shifts to talk of WordPress themes, it’s referring to those that make up the design and style of a published and public website. However, themes are also available for styling the backend of your site.

More recent versions of WordPress have ramped up the style factor quite a bit. Individual users can select from a variety of color schemes through which to view the dashboard. From the cool tones of “Ocean” to the seemingly Halloween-inspired “Ectoplasm,” many people can find a look that appeals to their day-to-day sensibilities.

But if it’s important for you to create a branded look that’s in keeping with your company’s color scheme, you may find these out-of-the-box selections just won’t cut it. That’s where admin themes come in pretty handy.

Here are a few that will do your site proud:

Modern Admin


If you want to display your WordPress admin a little differently but don’t want to spend hours on custom code, Modern Admin might help you. This admin template is retina-ready and comes equipped with five different color schemes including blue, green, red, yellow, and purple. Plus, the custom color picker ensures you can make the right selection for your dashboard.

This theme has some of the features of white label plugins, too. For instance, you can customize the login page, add a custom logo, change the dashboard icons, and more. It also includes import/export settings and can be easily updated within the admin panel.

A regular license costs $14, while the extended costs $70.

WP Quick


As its name suggests, WP Quick is an admin theme that can be implemented quickly. It comes with plenty of features to keep savvy folks satisfied but is easy enough to setup that newbies to while labeling can get the hang of it right away.

Along with the ability to customize the colors and fonts used, you can also streamline the dashboard to only show the widgets you want displayed. For instance, you can stop those pesky update notifications from appearing, customize the login page with a unique logo, and change the default site avatar.

It also works with multisite, so you can create a custom, branded dashboard across all of your client sites very quickly.

Easy Blogging


Of course, I would be remiss if I didn’t mention WPMU DEV’s own admin customizer, Easy Blogging. Though technically a plugin, it lets you customize every aspect of the “look” of your dashboard very much so in the way a theme would.

It comes with some presets that make configuration and setup a snap. For instance, one click activates “Easy Mode,” which removes some of the more complicated options from the dashboard and adds new icons and tooltips to make your clients’ user experience more intuitive.

Easy Blogging also has a “Wizard Mode” that gives new users a step-by-step walkthrough of how to use the dashboard. And of course, you can customize this mode to include the information that relates to your site. You can even add in help links wherever you want using a drag-and-drop interface.

And since it works with multisite, you can set it up once and apply it across all of your sites. Convenient? I think so!

Easy Blogging costs $40 by itself or $19.60 per month with a WPMU DEV subscription.

Forest - Revolution WordPress Admin Theme


The last admin theme I want to throw at you here is Forest. This is a theme designed to make your WordPress backend as exciting and engaging as the frontend.

It comes with two admin styles within which you can adjust the background darkness level, background image, color scheme, menu font, and content font. You can also enable a Quick Panel that makes it simple to adjust settings on the fly. Plus, you can adjust how the Quick Panel looks for an even deeper level of customization.

As with all the other admin themes mentioned here, Forest also lets you configure standard white label functions like setting a custom login logo and login image, custom footer text, and custom admin CSS. Plus, you can hide certain WordPress admin widgets from view.

Forest includes a Google Fonts chooser, Font Awesome Icons, and sports a retina-ready design. It’s also multisite-compatible. The regular license costs $14, while an extended license costs $70.

For more backend themes for white labeling your site, you should read our top 10 list of WordPress admin themes.

Wrapping Up

Whether you build many sites for a wide range of clients or just a few now and then, being able to take control of the the admin side of things can be incredibly liberating. White labeling not only gives you the freedom to create a dash that fits your brand identity, it also lets you create an interface that’s custom-tailored to your clients.

When deciding on which white label code snippets, plugins, or themes to use, try to keep a general idea of your goals in mind. What do you hope to accomplish with these changes? Do you just want to streamline the look of the backend of your site? Do you want to improve functionality for your clients? Both? It might even be helpful to create a list of the pros and cons of each modification before committing to them.

Do you make it a habit to white label your sites? What tools do you use to get the job done? Are you a flat-out coder or do you take the plugin approach? I’d love to hear your thoughts in the comments below. 

Image source: Derek Gavey.

http://premium.wpmudev.org/blog/white-labeling-wordpress/feed/ 1
Optimizing Your WordPress Database – A Complete Guide http://premium.wpmudev.org/blog/optimizing-your-wordpress-database-a-complete-guide/ http://premium.wpmudev.org/blog/optimizing-your-wordpress-database-a-complete-guide/#comments Thu, 16 Oct 2014 12:00:58 +0000 http://premium.wpmudev.org/blog/?p=132430 Your WordPress database stores all of your website content. This includes blog posts, pages, comments, and custom post types such as links, form entries, and portfolio items. It also stores website settings, theme settings, and plugin settings.

If you update your website regularly, your database will grow larger over time. A large database can greatly affect the performance of your website as it takes longer for your server to retrieve information from database tables. This is why database optimization is so important.

By removing unnecessary data, you can improve the efficiency of your database and make your web pages load quicker. Let us look at how this can be achieved.

Database optmization
Database optimization – boring but essential.

Understanding the WordPress Database

If you are using WordPress to publish content on the internet, I believe it is in your benefit to have an understanding of the core WordPress database tables; particularly if you are planning on optimizing your WordPress database.

WordPress currently has 11 core tables (this could, of course, change in a future version of WordPress). Most WordPress websites have dozens of tables because plugins save settings and other data in the WordPress database. Themes may also save settings and other data in your database.

If you check your own database, you will see the 11 tables listed below. All other tables in your database were created manually or created by a WordPress plugin or WordPress theme.

Let’s look at what each database table stores:

  • wp_commentmeta – Stores meta information about comments
  • wp_comments – Stores your comments
  • wp_links – Stores blogroll links (blogroll feature is deprecated, but can be added using Link Manager)
  • wp_options – Stores the options defined in the admin settings area
  • wp_postmeta – Stores post meta information
  • wp_posts – Stores data for posts, pages, and other custom post types
  • wp_terms – Stores post tags and categories for posts and links
  • wp_term_relationships – Stores the association between posts and categories and tags and the association between links and link categories
  • wp_term_taxonomy – Stores a description about the taxonomy (category, link, or tag) used in the wp_terms table
  • wp_usermeta – Stores meta information about users
  • wp_users – Stores your users

Check out the database description page on WordPress.org for more information about WordPress core tables.

How to Optimize and Repair Your WordPress Database

phpMyAdmin is the most common way to manage a WordPress database. If you are not using cPanel as your hosting control panel, your hosting plan may be using a different MySQL management tool to phpMyAdmin. Do not be too concerned about this as most database management tools have a similar interface and work in the same way.

You can also manage your WordPress database using a plugin such as Adminer (formerly known as phpMinAdmin). Although a database WordPress plugin can make accessing your database simpler, I would advise against managing your database in this manner as it is a large security risk. If you have a plugin such as Adminer installed and an unauthorized person gained access to your database, they could do anything they wanted to your website.

phpMyAdmin in cPanel
phpMyAdmin can be found in your main cPanel menu.

If you check your database, you will see two columns at the end: size and overhead. The size of a table depends on the amount of data that is stored in it. If more rows are stored in a table, the size of the table increases.

Overhead is temporary disk space that is used by your database to store queries. Over time, a table’s overhead will increase.

It is perfectly normal to have overhead in your WordPress database and it should not affect performance unless overhead gets high (though the actual amount of overhead that should be considered too high is a grey area).

WordPress Table List
The size and overhead of your database are shown on the right hand side of the table list.

* Please note that the above screenshot is taken from a new WordPress installation I created for screenshots. That is why the database prefix is still wp_. To make your website more secure, always change your WordPress database prefix through wp-config.php to something different.

Optimizing your database will remove the overhead and reduce the overall size of your database. Many developers note that optimizing a database is akin to defragmenting a hard drive.

Every database will, over time, require some form of maintenance to keep it at an optimal performance level. Purging deleted rows, resequencing, compressing, managing index paths, defragmenting, etc. is what is known as OPTIMIZATION in mysql and other terms in other databases. For example, IBM DB2/400 calls it REORGANIZE PHYSICAL FILE MEMBER.

It’s kind of like changing the oil in your car or getting a tune-up. You may think you really don’t have to, but by doing so your car runs much better, you get better gas mileage, etc. A car that gets lots of mileage requires tune-ups more often. A database that gets heavy use requires the same. If you are doing a lot of UPDATE and/or DELETE operations, and especially if your tables have variable length columns (VARCHAR, TEXT, etc), you need to keep ‘er tuned up.

You can optimize tables that are affected by overhead by using the SQL command OPTIMIZE TABLE. For example, you could optimize the wp_posts table by executing this SQL query:


There is no need to use an SQL command as phpMyAdmin allows you to optimize tables from the main drop down menu. All you need to do to optimize your database is click on the “Check All” box, select “Optimize table” from the dropdown menu, and then click on the “Go” button.

Optimize Your WordPress Table
Optimizing your WordPress database will remove any accumulated overhead.

Once you have optimized your WordPress database, phpMyAdmin will confirm that your tables have been optimized.

Successful Database Optimization
phpMyAdmin will confirm that your database has been optimized.

Another useful option you should keep in mind for future is “Repair table”. Repairing a table will help you fix a table that has become corrupted.

Repair Table
Repairing a table can fix a table that has become corrupted.

WordPress has a tool that allows you to repair and optimize your database. You can find out more about this tool in the Automatic Database Optimizing section of the WordPress.org guide on wp-config.php.

To use the optimization tool, you first need to add this line to your website wp-config.php file.

define( 'WP_ALLOW_REPAIR', true );

Once you have added the above line to wp-config.php and saved the file, you can access the optimization tool at http://www.yourwebsite.com/wp-admin/maint/repair.php.

WordPress Optimization Tool
The WordPress optimization tool lets you repair your database, or repair and optimize your database.

The optimization tool will attempt to repair each database table. From time to time, the script may not be able to repair certain tables.

Repairing a WordPress Database
WordPress will attempt to repair each database table.

If you do not successfully repair your database in the first attempt, simply run the optimization tool again.

Repairing the WordPress Database
If there are any problems during the repair, run the repair script again.

If you select “Repair and Optimize Database”, WordPress will optimize every table that has not already been optimized.

Optimized WordPress Database
The tool will optimize any table that has not already been optimized.

You do not need to be logged in to run the WordPress optimization tool. The downside to this is that anyone can access your script and execute it. Due to this, you need to remove the WP_ALLOW_REPAIR line from your wp-config.php file after you have used the optimization tool.

How to Remove Bloat From Your WordPress Database

Most WordPress databases store a lot of unnecessary data. This additional bloat makes websites slower and less efficient.

There are a number of things that add bloat to your website database. However, by following good practices, you can greatly reduce bloat, or even eliminate bloat entirely from your website.

Let’s take a look at the main causes of bloat in a WordPress database.


The WordPress revision system makes many WordPress databases unnecessarily large. First introduced in WordPress 2.6, the feature stores a copy of every draft and update of your blog posts. It is a useful feature as it allows you to revert back to older copies of articles and check earlier drafts.

Compare Revisions
Revisions allow you to look back at previous drafts and see the changes you have made.

Unfortunately, WordPress places no limitation on the number of revisions that are saved. If you are working on a long article, this could result in hundreds of revisions being saved. Even though the published article will only take up one row in your database, the corresponding revisions could use dozens or hundreds of rows in your database.

I am a big fan of the revision system, however I do not believe there is any real benefit to saving an unlimited number of revisions for each blog post. Thankfully, WordPress allows you to easily reduce the number of revisions that are stored.

To reduce the number of revisions that are saved, simply add the following code to your wp-config.php file.

define( 'WP_POST_REVISIONS', 2 );

Post revisions can be completely disabled by adding the following code to your wp-config.php file.

define( 'WP_POST_REVISIONS', false );

I would advise against disabling post revisions completely. While disabling post revisions will undoubtedly reduce the size of your database, it removes the fail safe system that revisions provide. Therefore, in the event of you closing your browser in error or losing your internet connection, you could lose everything you worked on since the last save of your draft.

Reducing the number of revisions that are saved, or disabling post revisions altogether, does not affect the revisions that are already saved. Therefore, post revisions attached to older blog posts will still be stored in your database.

Once an article has been published, there is little need to keep older post revisions, therefore you may want to consider removing all revisions from published articles. There are a number of WordPress plugins that allow you to do this (you can also remove revisions using MySQL; however you should be aware that problems can occur if you do not use the correct command).

For example, I used the plugin Optimize Database after Deleting Revisions earlier this year to reduce the size of my blog database by 59%.

The plugin allows you to define the number of revisions that are saved. It also lets you delete trashed items, spam items, unused tags, and expired transients. Specific database tables can be removed from the optimization process.

Optimize Database after Deleting Revisions has a scheduler too. It can be used to optimize your website automatically once an hour, twice a day, once a day, or once a week.

Optimize Database after Deleting Revisions
Optimize Database after Deleting Revisions features a scheduler that will optimize your database at set intervals.

Another option for deleting post revisions is Better Delete Revision. It provides a list of all revisions saved on your website. Unfortunately, there is no option to delete revisions individually; there is only an option to delete all revisions at once. The plugin does, however, have an option for optimizing all of your database tables to reduce overhead.

Better Delete Revision
Better Delete Revision can be used to delete revisions and optimize your database tables.

I would also like to briefly speak about autosaves. The WordPress autosave feature saves one autosave of your article every 60 seconds. This interval can be changed by adding the following code to your wp-config.php file.

define( 'AUTOSAVE_INTERVAL', 160 ); // Seconds

A lot of bloggers have advised disabling autosave as autosave saves multiple copies of your posts and pages. That is simply not true. Autosave only ever saves one copy of your article and will not use up much room in your database.

The autosave feature is an important fail safe that will help you if you lose your internet connection or close your browser by mistake. The feature does not use up much space in your database; therefore I encourage you to keep it activated.

Spam Comments

If your website receives a lot of spam, you may find that spam comments are taking up a lot of space in your database. By default, spam comments are automatically deleted after 30 days; however during that time they can take up hundreds or even thousands of rows in your wp_coments table.

A good anti-spam plugin can stop many spammers in their tracks so that the volume of spam comments you receive is reduced.

Akismet is a good solution as it allows you to discard obvious spam so that the comment is deleted from your database right away (though be concious of the fact legitimate comments could be deleted automatically).

Akismet Settings
Akismet allows you to discard discard obvious spam.

A useful plugin I used to use in the past is WPCommentCleaner. It allows you to batch delete all spam comments, unapproved comments, or approved comments.

There is less need to use that plugin now as WordPress added an “Empty Spam” button to the spam comment page that allows you to permanently delete all spam comments instantly.

Empty Spam
Spam can be deleted at the click of a button.

Spammers tend to target older articles that have good rankings in search engines. You can therefore reduce the amount of spam that your website receives considerably by disabling comments on articles that are older than a specified number of days. This setting is located in the discussion settings page in the WordPress admin area.

WordPress Discussion Settings
Closing comments on older articles can greatly reduce the volume of spam your website receives.

Spam comments can also be deleted using the following SQL command.

DELETE FROM wp_comments WHERE comment_approved = 'spam'

All comments awaiting approval can be deleted by using the following SQL command.

DELETE FROM wp_comments WHERE comment_approved = '0'

Since you can now delete all spam using the “Empty Spam” button displayed in the spam comment page, there is no real benefit to using an SQL query to delete spam from your database.

Deleted Items

Whenever you delete an item in WordPress, such as a blog post, page, image, comment, or link; it is sent to the trash folder. This is another fail safe system from WordPress that prevents you from deleting items by accident. Should you wish, the system allows you to restore items that are currently sitting in trash.

Unless you are deleting many items regularly, you should not need to worry about the space deleted items take up in your database. However, it is worth understanding how the trash system works, particularly if you have to delete hundreds or thousands of items from a WordPress website (whether it be posts, comments, images, or whatever).

Deleted items will continue to be stored in your database until the trash is emptied. By default, trash items are permanently deleted after 30 days.

The number of days before trash is emptied can be changed by adding the following code to your wp-config.php file.

define( 'EMPTY_TRASH_DAYS', 5 ); // 5 days

The trash system can be completey disabled by adding the following line of code to your wp-config.php file.

define( 'EMPTY_TRASH_DAYS', 0 ); // Zero days

I do not believe that disabling the trash system is a good move as it means that you cannot restore any items that were deleted by mistake. It is more practical to simply reduce the number of days before trash is deleted.

WordPress Transients

WordPress Transients offer developers a way of storing data temporarily in the WordPress database. Transient records are stored in the WordPress options table.

Expired transient records can add bloat to your database and make your website run slower. There are a number of plugins that help you manage your transients and delete expired transient records that are no longer needed.

The WordPress plugin Transient Cleaner has an option to delete expired transients and remove all transients. Delete Expired Transients also offers this functionality and the plugin allows you set up a daily task for deleting expired transients.

Transients Manager
Transients Manager allows to view the transients that are currently being used on your website.

Transients Manager is one of the best solutions for viewing your transients. It allows you to view, edit, and delete transients. However, the plugin does not have any options for bulk deleting expired transients.

Transients are not something you need to worry about on a regular basis, however it is worth checking them periodically to verify they are not affecting performance.

Unused Plugin and Theme Tables

99% of all WordPress plugins store settings and data in your WordPress database. Unfortunately, when you uninstall a WordPress plugin, this information is not removed.

This is by design. If data was removed every time you deactivated a plugin, you would have to configure the plugin again when you reactivate it. You would also lose any reports or content that the plugin generated.

However, if you have decided to stop using a plugin, or if you were simply testing a plugin, you will want to remove all data when you uninstall the plugin. A small number of WordPress plugins include an option on their settings page to remove all data, though the majority of plugins do not have this option.

Due to this, WordPress databases can accumulate a lot of additional bloat over time. It is not uncommon for a WordPress database to contain dozens of tables for plugins that were removed months ago, or even years ago.

WordPress themes also store settings in the WordPress database and these settings will remain in your database when you switch themes.

WPDBSpringClean highlights unused tables in your database.

Unused tables can be removed from your database manually through a database management tool such as phpMyAdmin. However, even if you have a good understanding of the 11 core WordPress tables, you will find it difficult to distinguish tables from active plugins and tables from uninstalled plugins.

A useful plugin to help you with this is WPDBSpringClean. The plugin will identify unused tables from uninstalled plugins and give you the option to delete them.

Plugins That Add Bloat

Each plugin you install on your website increases the size of your website database. The space that some plugins use in your database is negligible; but some WordPress plugins can add a lot of weight to your database.

Whenever you install a new WordPress plugin, you should review how much load it places on your server’s CPU and how much storage it uses in your database.

The following types of WordPress plugins are known for storing a lot of data in the database.

  • Anti-Spam Plugins – In order to protect your website, many anti-spam plugins save information such as IP addresses and email addresses. For example, Akismet stores a lot of data in the WP_CommentMeta table.
  • Security Plugins – Just like anti-spam plugins, security plugins keep track of a lot of information about spammers and hackers.
  • Statistic Plugins – WordPress plugins that provide traffic and analytical reports need to store large amounts of data in your website database. This includes views, visits, countries, browsers, operating systems, referrers, keywords, and more.
  • Related Posts and Popular Posts Plugins – WordPress plugins that showcase other posts are notorious for using a lot of CPU and a lot of database storage. These types of plugins need to store a lot of data in your database; such as the number of likes, shares, and views, that each page on your website has received.
  • Link Tracking Plugins – Most link tracking solutions give you the option of tracking the number of clicks to your links. This is useful for understanding visitor habits and seeing where outgoing traffic is leading. Unfortunately, tracking hits can take up a lot of space in your database.

Some developers are conscious of the fact their plugins use a lot of storage. Which is why some developers include an option in their plugins to clear data.

For example, I track links using Pretty Link. The plugin allows you to disable the built-in tracking system. Three tracking setups are also available: Normal tracking, an extending tracking configuration that offers more stats but slower performance, and a simple click tracking option that offers less stats but better performance.

Stats can also be deleted from within the settings area. The plugin allows you to delete all hits or hits within the last 30 or 90 days.

Other WordPress plugins allow you to reset data and remove the tables the plugin added. However, in general, most plugins do not feature an option to remove all data.

P3 (Plugin Performance Profiler)
P3 (Plugin Performance Profiler) can highlight problem plugins that are slowing down your website.

A great tool for checking what WordPress plugins are slowing down your website is P3 (Plugin Performance Profiler). The plugin will highlight the impact that each plugin adds to your page loading time.

If a plugin is using a lot of storage in your database, or slowing your website down considerably, remove it. I would only recommend keeping a slow WordPress plugin installed if it was essential to a website’s success. However, I believe there are always alternative solutions available to WordPress users.

How to Optimize Your Database Using a WordPress Plugin

Throughout this article I have given advice on how to optimize your database using phpMyAdmin and wp-config.php. If the thought of using phpMyAdmin worries you, you may prefer to use a WordPress plugin to optimize your database. There are a number of good options available.

WP Clean Up is a great way of quickly removing unwanted data. It allows you to remove revisions, drafts, comments, and more – all at the touch of a button.

WP Clean Up
WP Clean Up is one of the easiest ways of removing unnecessary data from your database.

WP-Optimize can be used to remove post revisions, drafts, spam comments, unapproved comments, comments in the trash, transient options, pingbacks, and trackbacks. It also includes a page that shows the data size, index size, and overhead, of each database table.

WP-Optimize is one of the most downloaded optimization plugins on WordPress.org.

Another popular optimization WordPress plugin is WP-DBManager. It is a feature packed plugin that lets you optimize and repair your database. Automatic backups of your website can also be configured.

WP-DBManager is a good plugin, but from a security point of view I would be careful using it as the plugin also allows you to empty tables, drop tables, and run MySQL queries. Therefore, anyone who gained access to your website using malicious methods would be able to do a lot of damage.

Those of you who use ManageWP to manage multiple websites can can optimize your database through your ManageWP Dashboard.

Final Thoughts

I have helped many website owners over the years with WordPress-related problems. Sadly, very few people appear to take steps to keep their website database running efficiently. There really is no excuse for this as it only takes a few minutes to configure a WordPress website correctly.

This is what I do on my WordPress websites to keep their databases optimized:

  • I reduce the number of post revisions to two by adding define( ‘WP_POST_REVISIONS’, 2 ); to wp-config.php
  • I employ strong anti-spam measures to greatly reduce the volume of spam added to my database
  • I review any items I delete and then delete them permanently (rather than keeping items in trash)

I also check my database periodically through phpMyAdmin. This gives me an opportunity to optimize the database tables and remove any unused database tables. From time to time I use an optimization plugin such as WP Clean Up, too. This allows me to remove transients and any other unwanted data that has accumulated over time.

For some WordPress websites, I have reduced the number of days items stay in trash from 30 to 5. However, I usually do not take this step as I am in the habit of deleting items permanently.

To reduce the number of calls to my database, I install a cache WordPress plugin. This does not reduce the size of my database, but it puts less stress on my MySQL server and ensures my pages load quickly.

Do you optimize your database? If so, what steps do you take? Let us know in the comments below.

Image credits: Designmodo from www.flaticon.com is licensed by CC BY 3.0, Icon made by Freepik from www.flaticon.com is licensed under CC BY 3.0

http://premium.wpmudev.org/blog/optimizing-your-wordpress-database-a-complete-guide/feed/ 11
Creating a WordPress Custom Functions Bible – and Snippets to Get You Started http://premium.wpmudev.org/blog/creating-a-wordpress-custom-functions-bible-and-snippets-to-get-you-started/ http://premium.wpmudev.org/blog/creating-a-wordpress-custom-functions-bible-and-snippets-to-get-you-started/#comments Wed, 15 Oct 2014 12:00:00 +0000 http://premium.wpmudev.org/blog/?p=132829 To hazard a guess, I would estimate WordPress developers realize the benefits of storing and reusing code snippets after their third or fourth WordPress site.

It not only ensures your development practices stay consistent from project to project, but also greatly improves your development efficiency.

Time saved from being able to avoid trawling through industry blogs and scouring recent projects functions.php files searching for that gem of a function you knew you once used can dramatically improve a project’s turnaround time.

Suggesting developers should save every snippet of code inside a mammoth “custom-functions-bible.php” file is not only completely ridiculous but also counterintuitive for development efficiency. Something as simple as creating a functions.php boilerplate or taking advantage of Adobe Dreamweaver’s snippets should suffice.

Code repositories are not only great ways to improve individual efficiency, but team efficiency, too. By encouraging your team of developers to take advantage of online resources such as using GitHub to build useful code repositories that are shared and updated within your team will help increase efficiency and learning.

In order to get you started, I have compiled a selection of some of my favorite custom functions for you to begin using throughout your projects.

Functions bible
Create a repository of your custom functions for easy access.

Limiting Words

Like many developers I often find myself needing to limit the length of a dynamic piece of content. Achieving these results by limiting the characters using simple PHP functions like substr() may be easy to implement but look messy for front-end users as the final word will often be chopped in half.

Aiming to limit your content by an amount of words is a much more elegant approach to this issue. Limiting a post by an amount of words can be achieved with the use of the built in WordPress function the_excerpt(); As standard the_excerpt() limits your content to the first 55 words, after which a […] is appended onto the post.

Great as this is, I often need more control over the length of the posts retrieved within a loop. To do this we have two options:

Option One – Controlling Excerpt Length Using Filters

My first recommendation would be to change the default limit of the_excerpt() using filters. The method outlined below simply needs to be added to your themes functions file and globally your posts will be limited to your desired amount.

function custom_excerpt_length( $length ) {
return 20;

add_filter( 'excerpt_length', 'custom_excerpt_length', 999 );

Option Two – Controlling Content Length Using A Custom Function

It is easy to run into issues with option one as it is a global solution to limiting the excerpt. Some developers may not be looking to limit the_excerpt() or may have numerous different custom loops which each require different excerpt lengths to be set. Unfortunately, option one isn’t going to solve these common issues.

By creating a custom function to look after this task allows developers more control over exactly what type of content to limit. The following function takes two parameters:

  1. $string – The string that needs be limited for example get_the_excerpt().
  2. $max_words – The maximum amount of words you would like to show.
/* Limit Your Website Excerpt */

function word_limit($string, $max_words){

$post_words = explode(' ', $string);

$count = count($post_words);

$post_words = implode(' ', array_slice($post_words, 0, $max_words));

if($count > $max_words):

return $post_words . '...';


return $post_words;



A Very Brief Overview Of How The Function Works

The function begins by taking the string and exploding it into an array, once in an array we are able to limit the array using the PHP function array_slice() and implode it back onto our page. If the content has been limited the function appends a “…” to the end of the post.

This function is a perfect example of how to correctly limit a piece of content on your website.

Removing WordPress Version Number

Improving WordPress security should not be overlooked on the sites you develop. I often speak to developers who have the “That Wont Happen To Me” attitude that I also once had. Trust me, coming from someone who has experienced the shame of being hacked, there is nothing more embarrassing and sole destroying than your site featuring a black screen containing the words “You Have Been Hacked By …” in a 125px font.

Developers who have experienced this type of hack will know the subsequent phone call to their client is not an enjoyable one.

I urge all developers to even take simple measures to help ensure their website’s security. For example, you are able to dramatically decrease your chances of being hacked by simply removing the WordPress version number from your source code using the following action in your functions.php file:

remove_action('wp_head', 'wp_generator');

Although this is an extremely simple security measure and will not guarantee full security, it does help to hinder hackers.

I recommend to wise readers taking WordPress security seriously to read WordPress Security: The Ultimate Guide by Kevin Muldoon.

Display All Site Settings

When developing themes and plugins I often find myself darting over to phpMyAdmin to check and modify specific settings.

The below code removes the need to manually access phpMyAdmin for these types of mundane tasks, by simply adding an “All Settings” tab that enables users to view an extensive list of site settings found within your database related to your site.

The function also ensures that the tab is only viewable to admin users and is an excellent and time efficient way to edit global website settings.


function all_settings_link() {
add_options_page(__('All Settings'), __('All Settings'), 'administrator', 'options.php');

add_action('admin_menu', 'all_settings_link');

Restrict Authors to Edit Only Their Own Posts and Media

Developing and managing large industry related blogs can be one hell of a task made even more challenging by the range of different authors you employ.

Often large WordPress blogs can have multiple bloggers adding media, creating posts and using the dashboard at the exact same time, and boy can it get confusing quickly.

A great way to improve your authors’ experience is to streamline their access within the WordPress Media tab. The following snippet allows authors to only view the media they have uploaded themselves, which allows for a much smoother blogging experience:

/* Only See Own Attachments */


function users_attachments( $wp_query_obj ) {

global $current_user, $pagenow;

if( !is_a( $current_user, 'WP_User') )

if( 'upload.php' != $pagenow )

if( !current_user_can('delete_pages') )
$wp_query_obj->set('author', $current_user->id );


Replace WP Admin

Delivering to clients a unique individual experience is crucial to customer satisfaction. This can easily be achieved by adding small personal touches throughout the site and the WordPress backend.

I have found something as small as switching the WordPress logo on the login screen to your customer’s branding really helps to deliver this experience to your clients.

The code below allows you to switch the login logo to a more preferable image by simply changing the attachment id:

add_action( 'login_head', 'login_logo' );

* Replaces the login header logo

function login_logo() {

$image_attributes = wp_get_attachment_image_src( 1, 'full' );
echo '<style> .login h1 a { background-image: url( ' . $image_attributes[0] . ' ) !important; }</style>';


I recommend taking this approach one step further by addressing two other small issues. The logo by default links through to the WordPress.org website and also has the HTML title “Powered by WordPress”. The following two functions ensure if clicked the user is taken to the site’s homepage and also modifies the title tag to contain the site title.

add_filter( 'login_headerurl', 'login_logo_headerurl' );

* Replaces the login header logo URL
* @param $url

function login_logo_headerurl( $url ) {
$url = home_url( '/' );
return $url;

add_filter( 'login_headertitle', 'login_logo_headertitle' );

* Replaces the login header logo title
* @param $title

function login_logo_headertitle( $title ) {
$title = get_bloginfo( 'name' );
return $title;

Removing Post Meta Boxes from Posts and Pages

When creating a WordPress page or post, users can often become overwhelmed by the amount of unnecessary fields found throughout the page, ranging from Custom Fields to Author Meta boxes.

Although they can be removed using the screen options drop down tab, I always make a habit of removing any fields that aren’t necessary to the website or user at the start of the project. After all why leave them there?

This extremely useful custom function makes use of the built in WordPress remove_meta_box() function. To remove a meta box that appears on both pages and posts we have to declare the function for each.


function remove_metaboxes() {

/* Posts */

remove_meta_box( 'authordiv','post','normal' ); // Author Metabox
remove_meta_box( 'commentstatusdiv','post','normal' ); // Comments Status Metabox
remove_meta_box( 'commentsdiv','post','normal' ); // Comments Metabox
remove_meta_box( 'postcustom','post','normal' ); // Custom Fields Metabox
remove_meta_box( 'postexcerpt','post','normal' ); // Excerpt Metabox
remove_meta_box( 'revisionsdiv','post','normal' ); // Revisions Metabox
remove_meta_box( 'slugdiv','post','normal' ); // Slug Metabox
remove_meta_box( 'trackbacksdiv','post','normal' ); // Trackback Metabox

/* Pages */

remove_meta_box( 'postcustom','page','normal' ); // Custom Fields Metabox
remove_meta_box( 'postexcerpt','page','normal' ); // Excerpt Metabox
remove_meta_box( 'commentstatusdiv','page','normal' ); // Comments Metabox
remove_meta_box( 'trackbacksdiv','page','normal' ); // Talkback Metabox
remove_meta_box( 'slugdiv','page','normal' ); // Slug Metabox
remove_meta_box( 'authordiv','page','normal' ); // Author Metabox


add_action('admin_menu', 'remove_metaboxes');


The custom functions featured in this post feature regularly within the functions.php files for my themes. My hope is that you also consider the use of them in your sites going forward.

There are absolutely hundreds of extremely useful functions that we simply don’t know exist as they have never been shared! Well this is the time to change that mentality.

I encourage all readers to share their own favorite snippets in the comments below, and just maybe, together, we can create our own “custom-functions-bible.php.”

http://premium.wpmudev.org/blog/creating-a-wordpress-custom-functions-bible-and-snippets-to-get-you-started/feed/ 10
Rock Your WordPress Forms With Gravity Forms Conditional Logic http://premium.wpmudev.org/blog/rock-your-wordpress-forms-with-gravity-forms-conditional-logic/ http://premium.wpmudev.org/blog/rock-your-wordpress-forms-with-gravity-forms-conditional-logic/#comments Tue, 14 Oct 2014 12:00:00 +0000 http://premium.wpmudev.org/blog/?p=132972 Creating a contact form in WordPress can be a daunting proposition. But once you get into it, the form usually comes together OK – as long as it’s a simple form.

Unfortunately, many forms turn out to be complicated, messy, and boring. Wouldn’t it be great if you could create a form that’s super clean, and that shows only what’s necessary for each particular user? And how cool would it be if you could wow your visitors with a dynamic effect, as different parts of the form appear, disappear, and reappear as they select various options?

With Gravity Forms conditional logic you can do all that – and more. Conditional logic isn’t exactly simple, but Gravity Forms makes it easy.

One of the problems is that a form with lots of varying choices can quickly expand, and the form becomes messy, crowded, and unwieldy. Overcrowded forms turn people off, and sometimes site visitors will just give up and go away after a quick glance. That’s exactly what you don’t want.

Even though the phrase “conditional logic” reeks of “advanced mathematics,” all it really means (in this case) is a way to set up an interactive form so that when a user clicks something on your form, some other thing changes on the form. The user might click a checkbox and, as if by magic, a previously hidden form field might appear. And at the same time, some other unnecessary form fields might disappear.

Let’s look at how you can easily set up your forms with conditional logic on your website.

Conditional logic is cool.
Conditional logic is cool.

Magic? No. It’s Conditional Logic

Form ready to be worked on.
Form ready to be worked on.

I’ll assume that you already know how to set up a static form with Gravity Forms, so now I’ll show you exactly how to get conditional logic working for you.

Let’s say you’re setting up an online application form people can fill out to join your PC Club – something very similar to the example form we’ll work on in the upcoming paragraphs.

At the top of the form, applicants have to fill in the usual information, such as name, address, e-mail address, etc. Simple. But things get complicated in the payment area near the bottom of the form, as you start creating form fields with lots of checkboxes and options.

As you can see in the graphic to the right, there’s a heading, a checkbox, a pop-up, and an explanatory line of text for those who want to pay now – and below that, there’s a section for those who want to pay later. There are several lines of text, checkboxes, pop-ups, etc. in this section, and all these various type weights, pop-ups, etc. look messy, and can be confusing to the user.

If you think this isn’t a big deal, consider that the applicant has already filled in several text boxes before arriving at this point in the form, and in some forms, there might be even more areas coming up, with lots of choices before finishing the form. You don’t want user fatigue, and you want a clean-looking form, so it would be great if you could clean up this area.

That’s what we’re going to do.

Getting Into Condition(al)

First, it’s too bad you can’t hide that messy pop-up menu and the explanatory text in the “PAY NOW” area until they’re actually needed. But wait. You can do that – with Gravity Forms conditional logic. Here’s how:

Pop-up menu.
Showing the pop-up area to be hidden.
  1. In the “Form Editor,” move your mouse over the field named “PC CLUB MEMBERSHIP,” which contains the membership-choice pop-up and the explanatory text for those who want to pay now. This is the field you want to become invisible and stay invisible until after the user checks the box under “PAY NOW.”
  2. As you move your cursor over the field, you’ll notice that the field becomes highlighted. Click the flippy triangle (highlighted in yellow in the graphic above) to expand the field so you can choose options that will apply to that field.
  3. Skip the “Properties” tab, and click into the “Advanced” tab.

    Inside the Advanced tab.
    Inside the Advanced tab.
  4. Near the bottom of the tab area, click the “Enable Conditional Logic” option – and then new options will appear where you can choose exactly what you want to happen, as you can see in the graphic above. Remember that you want to keep this field hidden, and only show it when an applicant chooses the “I’ll pay now with credit card” option under “PAY NOW.” The two lines directly under the “Enable Conditional Logic” checkbox contain pop-ups that let you choose options to “fill in the blanks” in these two lines.
  5. In the first line, press and hold the first pop-up, and choose “Show” from the options that appear.
  6. Then press and hold the second pop-up, and choose “All” from the options that appear. The result is a conditional statement that reads, “Show this field if All of the following match.”
  7. In the second line, choose options from the pop-ups until you get a conditional statement that reads, “PAY NOW is I’ll pay now with credit card.” Translated into more conversational English, this tells the form to initially not show this area of the form, but then show it when the user clicks the “I’ll pay now with credit card” checkbox under “PAY NOW.”
  8. When you’re finished, click the flippy triangle to close the field.
  9. Of course, at some point you’ll have to click the “Update Form” button, and then click the “Preview” button in order to view the form preview to see a close approximation of what the form will look like once you install it onto a page or a post.
Form after first round of conditional logic.
Our form after the first round of conditional logic.

SPECIAL USER TIP: If you want to see what your form is really going to look like as you’re making adjustments – to get a better view than the preview – install the form onto a page or post, and then open it in a separate browser window. Keep that window open off to the side, and then every time you update the form, just refresh the page in that open window, and you will see the changes you made as they will actually look in your finished project.

I’ve used a yellow keyline in the graphic above to show you that the form is a bit cleaner, because now when the form first appears on the page, the pop-up and the explanatory line are no longer visible in the “PAY NOW” area. And those two elements will only become visible if the user checks the box in the “PAY NOW” area.

Nice But…

…You can do better.

The form is still crowded, and there’s still the possibility of confusion for the user because all the choices and explanatory text are still visible in the “PAY LATER WITH CHECK” area.

It’s distracting, but it won’t be a problem for much longer.

Conditional logic settings.
Conditional logic settings.

You want everything between the “PAY NOW” area and the “SUBMIT” button to disappear when a user chooses to pay with credit card in the “PAY NOW WITH CHECK” area. Here’s how to make that happen:

  1. In the “Form Editor,” move your cursor over the “PAY LATER WITH CHECK” form field, click the flippy triangle to expand the field.
  2. Get into the “Advanced” tab.
  3. As before, check to enable conditional logic.
  4. Set the conditional options as shown in the graphic above. Be sure you choose Hide this time, because you want to hide this field until it’s needed.
  5. Close the form field when you’re finished.
  6. Update the form, and view the preview or the actual page (as described above) to check your work.

You have now set the conditional logic so that this area of the form will be visible until the user checks the box in the “PAY NOW” area – at which time this area will disappear.

Do it Some More

Final form area.
The final form area.

Now do the same thing with the other form fields that you want to hide: Open the fields, choose the conditional logic option, set the conditional options, close, update, and view to check your work.

As you can see above, the user has clicked the “PAY NOW” option, and conditional logic has done its thing. Not only has it brought the membership-choice option into view, but it has caused all the now-superfluous “PAY LATER WITH CHECK” stuff to disappear. All the unnecessary distractions are gone.

But what if the user suddenly decides to not pay now, and wants to pay later, by check? No problem. Soon as the user deselects the credit-card option, all the “PAY LATER WITH CHECK” information reappears.

See for Yourself

Play the video below to see the magic for yourself. Areas of the form will disappear and reappear depending on what the user clicks.

We’ve only scratched the surface of conditional logic, but now that you understand how it works, it’s a sure thing you’ll think of lots more ways to use it.

Gravity Forms is a premium plugin, which means you have to buy it. It’s available under three different licenses, depending on how many sites you want to use it with. Gravity Forms offers great support for their product, they have lots of add-ons to extend the basic plugin, and their documentation is well above average. Check out their site to find out more.

We often over use “Cool!” when describing things we are think are, well, cool. But, really, when you try it for yourself, and see how Gravity Forms conditional logic can transform your own forms, you won’t be overdoing it one bit if you exclaim, “How cool is that?!”

Do you use conditional logic on the forms for your website? Let us know in the comments below.

http://premium.wpmudev.org/blog/rock-your-wordpress-forms-with-gravity-forms-conditional-logic/feed/ 6