WPMU DEV's Blog - Everything WordPress » WordPress Tutorials - WPMU.org http://premium.wpmudev.org/blog The WPMU DEV WordPress blog provides tutorials, tips, resources and reviews to help out any WP user Sun, 21 Dec 2014 13:00:00 +0000 en-US hourly 1 http://wordpress.org/?v=4.0.1 How to Use a WordPress Shortcode Outside the Post Editor http://premium.wpmudev.org/blog/wordpress-shortcode-outside-post-editor/ http://premium.wpmudev.org/blog/wordpress-shortcode-outside-post-editor/#comments Sat, 20 Dec 2014 13:00:46 +0000 http://premium.wpmudev.org/blog/?p=135529 Shortcodes in WordPress are amazing. They are essentially macros that allow you to place content anywhere on your site.

For example, instead of inserting a whole bunch of images to create a gallery, you simply use the shortcode [ gallery ]. WordPress offers a few shortcodes by default and there are hundreds to choose from via available plugins.

There are a couple of places you may want to use shortcodes outside of your post content. Sidebar widgets for one, and perhaps somewhere inside your theme (in the footer, for example). In this post we’ll take a look at how you can make this happen.

Enable Shortcodes in Widgets

Some widgets you use via plugins may support the insertion of shortcode, however the default text widget does not. To make sure shortcodes are indeed applied properly you can use a single line of code, pasted into your theme’s functions.php file.

add_filter('widget_text', 'do_shortcode');

If you are using a third-party theme (any theme you didn’t make yourself), you really should use a child theme, take a look at our guide to child themes on how to make it happen. You can, of course, also create your own plugin.

Using Shortcodes in Theme Files

If you would like to output a shortcode in theme files, you can do that pretty easily as well.

All you need is the do_shortcode() function, which should be wrapped around the shortcode itself. Here’s an example:

Now why would you do this if it is hard-coded into a theme? In many cases theme authors prefer to go with a shortcode if they are hard-coding some functionality, which will be filled up using theme options but uses elements contained in a shortcode.

Let’s presume that the theme author provides a shortcode for a special gallery, which you can create using [specialgallery id='44,124,342'] where the IDs are images to display. If the theme uses this gallery type in the header on the home page, the theme could provide the options to select the images on an options page, then it could be output using this shortcode.

The benefit here is standardization. All galleries which look the same are the same, meaning they can be modified together.

]]>
http://premium.wpmudev.org/blog/wordpress-shortcode-outside-post-editor/feed/ 0
WordPress Plugins: When to Buy, When to Download Free http://premium.wpmudev.org/blog/wordpress-plugins-when-to-buy/ http://premium.wpmudev.org/blog/wordpress-plugins-when-to-buy/#comments Wed, 17 Dec 2014 13:00:16 +0000 http://premium.wpmudev.org/blog/?p=134714 When I was just starting out with WordPress I remember working on a client site which needed a slider. Rather than use the javascript slider I’d previously been using on static sites I decided to look for a plugin. But being new to WordPress I didn’t really know what I was looking for, so I spent the best part of half a day trawling the WordPress Plugin Repository and googling, all the time testing out ones that looked like they might do the job.

Bear in mind that this was nearly five years ago and WordPress was nothing like it is now: the plugin repository had a fraction of the plugins it now has and there weren’t as many high quality developers coding free or premium plugins. In the end I chose a $20 plugin, which I still had to hack a bit to get it to do exactly what I wanted. But my pleasure at finding a solution was marred when a friend and colleague did that teeth-sucking thing when I told him: he was shocked that I’d forked out cash for a WordPress plugin when there were so many free ones available.

Things have changed since then. The quality and range of free plugins increases continuously, while at the same time there are some fantastic premium plugins available (many of them here at WPMU DEV), which can save a developer many hours of work and be extremely cost effective in the long run.

So if you haven’t spent years downloading, buying, developing and testing WordPress plugins, how do you know when you should get one for free and when you should hand over your hard earned dough?

In this guide I’ll explain the difference between free and premium plugins, as well as the variations in between, and give you some tips on making that decision. I’ll also warn you about the plugins you should avoid, be those free or at a price.

I’m going to look at two main areas:

  • Sources of free and premium plugins, what they offer and how to use them.
  • Deciding whether to buy or download free, based on specific criteria.

Sources of Free and Premium Plugins

But first, let’s see exactly what’s meant by free and premium plugins, and the options for buying them.

Free Plugins

A free plugin may be entirely free or it may be a (permanently) free version of a premium plugin. This doesn’t include a free trial that you’ll need to pay for if you want to keep it.

In most professional spheres, there is a mistrust of anything that you can get for free. After all, there’s no such thing as a free lunch, right? Well, with WordPress there is. Not only a free lunch, but in some cases a free six course banquet.

The Good

The WordPress plugin repository gives access to thousands of free plugins
The WordPress plugin repository gives access to thousands of free plugins

The WordPress Plugin Repository is far and away the best place to get free plugins. If you find a free plugin elsewhere, I would always recommend checking if it’s in the plugin repo. Installing it will be easier and you’ll know that the version you’re downloading has been tested and should be stable and bug-free.

Plugins you’ll find here range from small plugins uploaded by developers doing this in their spare time to complex plugins that can completely transform your site’s functionality or performance. Some plugins with premium features but not the premium price tag are:

This is just a small selection of the many free plugins which will give you comparable features to any premium plugin available and have been downloaded millions of times. You may be wondering how the developers manage to make a living if they’re making quality code available for free. The answer to this will vary between developers, but in some cases (e.g. WooCommerce), there are additional premium add-ons, which you can buy, while in others (e.g. JetPack) the developer makes money elsewhere, either via a service like wordpress.com, or through consultancy. Releasing free plugins is a great way to raise your profile and give something back to the WordPress community at the same time, which is why some of the best developers do it.

The Bad

However, not all in the plugin repository is a bed of roses. At this moment there are 34,623 plugins for download and in all they’ve been downloaded 787,677,233 times. A sizeable minority of those plugins haven’t been updated for over two years, or haven’t been confirmed as compatible with the latest versions of WordPress.

When a new version of WordPress is released, the more diligent plugin developers will test their plugin to ensure it’s compatible and if it’s not, they’ll fix it. They’ll quickly upload the new version or confirm that the current version is compatible. How quickly this happens will be more of an issue with larger WordPress releases. If a plugin is compatible with WordPress 4.0 for example, but not 4.01, it’s unlikely you need to worry. But if you’re running the latest version and you’ve found a plugin which is only compatible up to version 2.8, then there’s a decent chance it won’t work as it should or it may conflict with other plugins you’ve installed or with WordPress itself.

The Ugly

There are plenty of alternative sources of free WordPress plugins (just try a Google search), but I would advise extreme caution before using them.

A reputable developer knows that the plugin repository is the trusted source so will distribute their plugins there. This means you’re unlikely to find anything good elsewhere which isn’t in the official repository. In addition to this, there’s a chance the plugin could contain malicious code or spammy content such as backlinks. Most users looking for plugins don’t want to or can’t delve into the plugin’s code, and so won’t be able to spot any problems.

Some “freemium” vendors will make their free plugins available on their own site as well as in the plugin repository. Again, I would still advise downloading from the repository to be sure the code is stable.

Premium Plugins

The number of premium plugins available and the range of tasks they’ll help you accomplish continues to grow. At WPMU DEV alone we have around 150 plugins which you can buy individually or access as a subscriber. Between them, other vendors sell thousands more. One of the main decisions you’ll need to make when buying premium plugins is whether to buy or subscribe to them and sometimes which level of purchase to opt for, so let’s take a look at these options.

One-off Purchase

If you’re working on a quick project with a tight budget and don’t envisage using the plugin again, a one-off purchase may be the best option. This can be a lot cheaper than subscription, but does have some risks.

With many plugin vendors, a one-off purchase means you won’t have access to updates after a set time (normally one year), or that you won’t have access to support after a set time, or even at all. So if you want to install updates to the plugin – including security updates – in the future, you might be better off going for a license or subscription.

Having said that, there will be times when you need a plugin for a project with limited duration, or a site which won’t be in existence in a year. In these cases it makes sense to save some cash and go for the single plugin subscription.

On some rare occasions you may find a plugin that you only have to pay for once and still get access to updates and sometimes support for the lifetime of the plugin. Chances are the fee will be larger than for plugins with one year of updates and support included, but it may prove to be better value over the long run. Although be aware that if the deal seems too good to be true, that may be for a reason!

Single Plugin License

The next step up from one-off purchase of a single plugin is to buy a license for that plugin. This generally gives you access to updates and support for a year. Depending on the way the vendor’s purchasing system works, you may be automatically signed up for renewals each year or you may be prompted to renew when your year is close to expiring.

This gives you the flexibility of buying the plugin for your first year and then updating it if you need to; if the site you bought it for isn’t in use anymore, then you won’t need to renew.

Purchase Options

The Gravity Forms plugin has three purchase options
The Gravity Forms plugin has three purchase options

Some plugins give you a few purchase options to choose from. Gravity Forms, for example, has three levels of subscription, with the lowest being for one site with no add-ons/extensions included, and the highest for unlimited sites with access to all of their add-ons. Which options you choose will depend on how you’ll be using the plugin and whether you need extensions, but all vendors will let you upgrade if you need to, so it’s worth going for the lowest option you need right now and then upgrading later on.

Subscription to a Library or Club

The most comprehensive way to purchase plugins is to subscribe to a vendor’s club or library, giving you access to all of their plugins for an annual fee.

Again, if you choose not to renew after a year you’ll still have the plugins on your site, but you won’t have access to any updates or support. If you anticipate using more than two or three of a vendor’s plugins this can be the best value way to buy plugins.

Subscribing to WPMU DEV gives you access to hundreds of premium plugins and themes

WMPU DEV is a great example of this model: you can pay from as little as $19 for a one-off purchase of one plugin, or you can subscribe to the full library of themes and plugins for an annual fee.

Freemium Plugins

An increasing number of WordPress plugins are now “freemium,” which means there’s an element of free to them and an element of payment. There’s more than one model for freemium plugins:

Free Basic Version, Premium Upgrade

This is probably the most common type of freemium plugin. A large number of plugins in the WordPress plugin repository are free with big siblings that you can upgrade to for a price.

The Coming Soon plugin has a free and premium version
The Coming Soon plugin has a free and premium version

The Coming Soon plugin, for example, creates teaser pages and maintenance mode pages and is free from the plugin repository. If you want advanced features you’ll have to pay for the premium version, which you buy direct from the vendor. Many users will find that the free version meets their needs just fine, while others who need more advanced functionality or access to support, will upgrade.

Beware plugins whose free version is so lacking in features that you have to upgrade to get anything decent. You may be happy to do this if the pro version is good enough, but it’s not a model many developers and users are comfortable with.

Free Core Plugin, Premium Add-ons

Sometimes you’ll find that the core plugin you need is completely free, but you can add more modules to it in the form of add-ons or extensions: plugins you pay for which work with the core plugin.

A good example is the WooCommerce e-commerce plugin. For a sizeable proportion of stores, the core plugin will give you everything you need to sell online, but for stores needing extra features, those extensions will be necessary and worth the cost if they help you sell more.

Free Plugin, Premium Themes

As well as offering premium add-ons for WooCommerce, WooThemes also sell premium themes designed to work with WooCommerce.

The Jigoshop plugin is free but you can buy premium themes to use with it
The Jigoshop plugin is free but you can buy premium themes to use with it.

Jigoshop is another e-commerce plugin with a similar model: the core Jigoshop plugin is free with premium extensions available as well as premium shop themes.

Free Plugin, Premium Support

Sometimes as well as, or instead of, offering premium extensions for a free plugin, a vendor will offer premium support and advice to users of the plugin.

The WordPress SEO by Yoast plugin is free, but you can buy premium extensions for it and you can also pay for support services such as SEO reviews. You don’t need these to be able to use the plugin but if you’re an advanced user wanting to get the most from it, they will help.

Deciding Whether to Go Free or Premium

Once you know the different options available to you, you need to decide what’s most appropriate for your site. This may be your personal website or it may be one of a number of projects you’re working on for yourself or clients: this will impact on your decision, but more of that shortly.

I’m going to examine five criteria and identify what impact they might have on your decision to spend money or not:

  • Quality
  • Budget
  • Skill level
  • Future-proofing
  • Time

Quality

The quality of a plugin will always be the most important criteria when it comes to choosing it. No one wants to install crappy plugins on their site.

By quality I’m referring not only to how well a plugin is coded, but what its features are. A good plugin will include just the features it needs to do its intended job, achieved with as little code as possible, with well-written code that’s compliant with the WordPress coding standards. A great plugin will also have documentation that helps you install and use it, and maybe support, too.

In some cases you’ll find that you can get excellent quality without paying a dime, in which case I say go for it. I’ve given some examples of great free plugins above, and would estimate that 95 percent of projects needing that functionality will get everything they need from these high quality free plugins.

But if you can’t get the features you need for free, or you need better documentation or support, then consider paying extra for the quality. If you have to spend hours getting to grips with or hacking a plugin that isn’t right for you, the money invested in a premium plugin could well be worth it. Especially if you’re being paid for your time. Which brings me to…

Budget

Budget is a no-brainer – after all, if you haven’t got the cash to spend on a plugin, you have no choice but to find a free one. If you’re being paid for your work and you can charge your client or boss for the cost of a premium plugin that meets the project’s needs better than any free ones, then it makes sense to pay up.

But there will be times when paying for a premium plugin (or buying a subscription to a suite of plugins), will be a cost-effective solution even if you can’t pass on the cost. For example:

  • You’re working on a client project with a fixed budget, and buying a premium plugin will save you development time. This is time you can use to earn money on another project.
  • You’re working on your own site, and a premium plugin will reduce your development time and/or help you to get more users or customers. You’re already investing your time in this site and for business sites in particular, the cost of a premium plugin isn’t a big investment when offset against the extra money you could make by using it.
  • You can use the premium plugin again and again on other projects, while the free alternatives don’t quite meet the needs of other projects or will need different hacks. The more you use a premium plugin, the better value it is. I’ll cover this in more detail shortly.
  • You might not use this plugin again, but you’re likely to have a use for other plugins, which come in the same suite. You’ll need to weight up the costs against the number of plugins you’ll use and on how many sites, but this often turns out to be a better investment than you expect.

Skill Level

An experienced, highly skilled developer will be able to take a plugin that doesn’t quite do what he or she wants, and use it as the basis of a new plugin that does. This is how a lot of plugins in the plugin repository started out – as variations on existing plugins, which either didn’t quite have a certain feature set or weren’t being developed or updated anymore.

But if you’ve never written a plugin in your life and aren’t comfortable with code, or you’re just starting out with WordPress development, you’re unlikely to be successful if you try this. In which case, if a free plugin doing the job you need doesn’t exist, then you might need to find a premium alternative.

Another scenario is when you need detailed documentation or support to help you work with your plugin. You’re much more likely to get these from a premium plugin developer. While each plugin in the repository does have its own support page and some developers are very good at answering questions, you can’t rely on this if you need answers fast. With a premium plugin you’ll be paying for support as well as code, and with the best plugins and vendors you’ll find that you have access to one-to-one support where somebody will do everything bar actually holding your hand as you install and configure the plugin, should you need it.

Future-proofing

There are three important considerations when identifying how you will use the plugin in the future:

  • Is the plugin likely to be updated regularly?
  • Do you anticipate using it on a number of projects in the future?
  • Does it give you access to a library of other plugins you can use on this and future projects?

If the site you’re building will be managed well in the future (which it really should be, or why build it?), it needs to be kept up-to-date as new versions of WordPress are released. This means that plugins will also need to be kept up-to-date, tested and updated if necessary to ensure they’re compatible. Good plugins will also be developed to expand their feature set and reliability and respond to changes in users’ requirements. There are free plugins that meet all these criteria just as there are some premium plugins that don’t, but it will be a consideration when you’re choosing the best plugin for you.

If you plan on using a plugin time and time again, then paying for it makes more sense than if you’re only going to use it once, as the cost is spread out. This will also influence whether you pass the cost on to a client. For example, I pay for the premium Gravity Forms plugin, which I use on the majority of client sites I build. I don’t pass the cost directly on to clients as I use it so often. However when I developed an e-commerce site for a client last year using WooCommerce, I had to buy two premium add-ons with features that were very specific to that project. I passed the cost on to the client, invoicing them for the cost of the plugins. This saved them money as my development time to build this functionality from scratch would have cost them much more.

Even if you don’t anticipate using this plugin frequently, it may give you access to other plugins which you will use. You can buy WPMU DEV plugins as one-offs or you can subscribe to the library of plugins and themes, which costs more than buying just one plugin, but gives you access to hundreds of plugins and themes. Last year I needed the Support System plugin for a site I manage, and decided to subscribe to the full WMPU DEV suite instead of buying just the one plugin. I’ve since used other plugins on a number of client sites, saving me time and money in the long run.

Time

I’ve already mentioned the time involved in developing your own plugin or hacking one that doesn’t do quite what you need. Installing and configuring a plugin with poor documentation or support also costs you time, as does installing a plugin only to find that it’s not right and having to find another one instead.

At the very beginning of this post, I described a situation I was in some years ago when I had to find a slider plugin for a client job. It was the first WordPress build I’d done for a client so I had no idea where to look for plugins. I also didn’t have a network of people I could ask for ideas. So I spent half a day trawling through the plugins repository and Google, and testing plugin after plugin, until eventually I found what I needed.

If time is tight and you need a solution that can be quickly and easily installed and configured, perhaps using settings screens rather than functions or hooks to activate and configure the plugin, then it makes sense to go for a high quality plugin that’s as quick and easy as possible to set up, even if you have the skills to work with another plugin that requires you to write some extra code.

However this doesn’t always mean you have to spend money. This summer I worked on an intranet build for a client with some tight timescales because a team was about to start work adding content to the site. The build needed some custom work with post metadata. Normally I would have coded this myself but in the time given this just wasn’t possible, so I used the Advanced Custom Fields plugin and made some quick customizations to my theme to make it work in the way I needed it to. In this case, it didn’t cost me any money as that plugin is free, but in some cases you may have to pay for a plugin if time is tight and you don’t have the flexibility to code your own or adapt an existing free plugin.

Summary

There isn’t one hard and fast rule when it comes to deciding whether a free or premium plugin is right for you and your project, but there are some things to consider:

  • The quality of free vs premium plugins available
  • Whether you have the budget for a premium plugin or can pass the cost on to your client or boss
  • Whether you have the skills to install and configure a free plugin with poor documentation and no support, or to hack a free plugin to get it to do what you need.
  • Whether you will use this plugin, or other plugins in the same suite, time and time again on future projects.
  • How much time you have to develop your own plugin or test free plugins in the search for the best one.

In many cases you’ll be able to find a free plugin that is of just as high quality as any premium one, but there will be times when there just isn’t one available. On those occasions this guide should help you decide which approach to take.

What are you experiences with free vs premium plugins? Let us know in the comments below.

]]>
http://premium.wpmudev.org/blog/wordpress-plugins-when-to-buy/feed/ 4
Catch MailChimp Updates in WordPress Using Webhooks http://premium.wpmudev.org/blog/mailchimp-updates-wordpress-using-webhooks/ http://premium.wpmudev.org/blog/mailchimp-updates-wordpress-using-webhooks/#comments Tue, 16 Dec 2014 13:00:19 +0000 http://premium.wpmudev.org/blog/?p=134944 Do you want to be able to track your WordPress users as they subscribe and unsubscribe from your MailChimp lists?

Of course you do, but your MailChimp plugin is probably no help beyond generating that subscribe form. What you need is MailChimp webhooks.

In this article, I’ll show you how to build a simple plugin to update your WordPress site with all your MailChimp list activity.

What Is A Webhook?

A webhook is simply a url that gets called when a certain event takes place, passing pertinent data about the event.

This provides a simple method for one application to take action based on an event happening in another and is perfect for our scenario of wanting to keep track of subscribes and unsubscribes.

Hooking Up MailChimp And WordPress

In this scenario, when a user is subscribed to, or unsubscribed from a list (an event), MailChimp will post the relevant data to a specified URL on our WordPress site that will use the event data to carry out some relevant processing such as updating a subscribed flag.

MailChimp packages up data about the action as a standard HTTP POST, so it is, to all intents and purposes, akin to a form submission where the form’s action is the webhook URL.

MailChimp also does its best to ensure that the webhook is successful. If it doesn’t receive an HTTP 200 (all ok) return code from the webhook URL then it will re-call the webhook. Not as robust as a full-blown message queue system but decent enough for our needs.

So, to get MailChimp and WordPress talking we need to tell MailChimp the URL of the webhook and when to call it and we need to extend WordPress to handle that call.

As you’ll need information from your WordPress configuration to set up MailChimp, let’s start with setting up WordPress.

Setting Up WordPress

You’ve got two options when it comes to setting up WordPress:

  1. Use our MailChimp Integration plugin, which has webhook support built-in.
  2. Use this custom plugin to use in conjunction with your current MailChimp plugin.

Using WPMU DEV’s MailChimp Integration Plugin

Once you’ve installed or updated to the latest version of the MailChimp Integration plugin, head to Settings > MailChimp. Enter your API key, select the list you want to synchronize and configure any of the other options. Then, once you’ve saved your settings, you will see the Webhooks options appear.

Screengrab of the webhook section in the MailChimp Integration plugin settings page
just 2 options to set up webhook support in WPMU Dev’s MailChimp Integration plugin

There are just two options to set:

  1. Specify a unique webhook key : This acts as a low-fi security mechanism as the webhook function won’t process any request that doesn’t contain the security key
  2. Action to take when user unsubscribes from list : Decided whether to delete a user from your WordPress site when they unsubscribe or merely mark as unsubscribed

When you’ve set these two options, click on Save Changes.

Under the webhook key text box you’ll see a URL listed. Copy this and head over to MailChimp.

Using the Custom Plugin

First thing to do is download and install the plugin. When you have the plugin installed, go to Settings > MailChimp Webhooks.

Screenshot of the WordPress Webhooks plugin's settings page
Control how the MailChimp events are handled by your WordPress site

There’s not much here but it’s fairly important. The options are as follows:

  1. Create new user on subscribe? If checked, a subscribe event will create a new user in your WordPress site with the role of subscriber, if none currently exists.
  2. Delete user on unsubscribe? If checked, when a user unsubscribes they will be deleted from the WordPress site.
  3. Specify a unique webhook key? Like the MailChimp Integration plugin, the webhook function won’t process any request that doesn’t contain the specified security key
  4. Write activity to log? Checking this option will cause all activity to be written to a log – useful for debugging.

The plugin uses the email address to check for existing users and if users are not being created and deleted then a unique flag is added to the user record so that, as a site owner, you can quickly see if the user is subscribed or not.

Once you have configured the settings and added your webhook key, click on Save Changes.

You’ll also see that the webhook URL listed under the webhook key has changed in line with your webhook key. Copy this URL as you are going to need it for the next step, configuring MailChimp.

Configuring Webhooks In MailChimp

Webhooks in MailChimp are configured on a per-List basis, so jump into your MailChimp account, find the appropriate List, click on Settings > Webhooks and then on the Add A New Webhook button.

You’ll be presented with a form like this:

Screenshot of the webhook configuration form on MailChimp
Select which events you want to capture and how they occurred

Callback URL

This is where you paste the webhook URL list on the WordPress plugin’s settings page.

What type of updates should we send?

Fairly self-explanatory, this a list of events that you can track. There are a number to choose from but keep in mind that, out-of-the-box, the WordPress plugin you’ve installed only actions subscribes and unsubscribes.

Checking all the events doesn’t hurt but if you want to action more events then you’ll need to extend the plugin (see later).

Only send updates when a change was made by:

The right-hand list of checkboxes allows you to select events based on how the event was initiated.

  • A subscriber: you’ll definitely want to check a subscriber as this covers all the manual actions, such as clicking on a link in an email.
  • Account admin: that’s you and I think this is worth keeping as it means that any changes you make in the MailChimp admin interface, except for imports, will be passed through to your WordPress site.
  • Via the API: if, like the majority of WordPress / MailChimp users, you are just using a MailChimp plugin to generate a sign-up form then checking this will ensure that you can track those sign-ups and add the users to your website.

It’s worth reiterating that bulk imports do not fire webhooks, which is understandable (for big lists) but annoying (for smaller lists). One apparent workaround is to bulk import to a temporary list and use the bulk action move to move the subscribers to the intended destination: this will fire the webhook for each new subscriber.

Obviously, you don’t want to do this for a very large list.

When you’ve checked all the appropriate boxes, click on Save and the webhook will be created.

You’ll notice that you can add multiple webhooks for the one list which might be useful if you wanted several sites to track the same List.

Testing Your Webhooks

The easiest way to test your webhook is to manually add a subscriber to the List in MailChimp using the form at Add Subscribers > Add Subscribe.

Complete the form and click on Subscribe and if MailChimp confirms the add was successful go to back to your WordPress admin interface and click on Users.

Look for the user with the email address that you added in MailChimp (if it did not already exist and you have set the WordPress plugin to Create new user on subscriber to true then the user will have been created) and click to Edit. Scroll down to the bottom of the profile page and you’ll see the following:

Screengrab of the MailChimp Newsletter section on the User Profile screen showing whether the user is a subscriber or not
Keeping track on whether users are newsletter subscribers is easy with webhooks

Now go back to MailChimp, click on Manage Subscribers > View Subscribers and you’ll get a list of current subscribers.

Click in the checkbox next to your test subscriber and two new action buttons appear at the top of the page, Actions and Delete. Either click on Actions > Unsubscribe, or Delete and then Confirm.

Now back into WordPress and if you are not deleting users on unsubscribe the MailChimp Newsletter subscriber checkbox will be empty, otherwise the user will have been deleted.

You’ve now configured MailChimp webhooks and in doing so can now track changes to your subscriber list that take place outside of your WordPress site which in the majority of set-ups will be the norm.

Once you are tracking these (un)subscribe events, you can start to think about how you might be able to leverage this data to encourage newsletter sign-ups. One obvious use is to provide subscriber only content and we’ll be taking a look at how to implement such a social paywall in an upcoming post.

How The Custom Plugin Works

By virtue of the fact you are reading this, you must be (slightly) curious as to how this works on the WordPress side of things. Good on you.

The plugin does the following:

  1. Sets up the webhook URL,
  2. Intercepts calls to the webhook URL, works out what the event is and then passes the data to the appropriate handler (subscribe / unsubscribe),
  3. Adds the MailChimp Newsletter section to the User Profile display, and
  4. Creates the settings page using the Settings API.

I’m not going to go through the settings page creation as I’ve covered this in previous posts, so let’s start with setting up the webhook URL.

Setting Up The Webhook URL

When the plugin is activated it runs an initialization function. This function hooks into the init action to make use of the add_rewrite_rule and the add_rewrite_tag functions to change a request for <site name>/webhook?key=yourkey to <site name>/index.php?webhook=1&key=yourkey.

The exit() command ensures that no subsequent processing takes place.

Actioning The Webhook Event

All webhooks requests are initially handled by the one function which:

  1. Checks to make sure the request contains data ($_POST),
  2. Checks that the key supplied matches the key you set in the plugin’s settings, and
  3. Determines the type of event and calls the appropriate handler.

You’ll notice that an activity log is updated (this is written to the plugin’s directory) and that all the events are catered for, although only the subscribe and unsubscribe functions have been fleshed out.

If you want to also take action on a cleaned, upemail or profile event then you’ll need to expand these functions in the plugin.

Handling A Subscribe Event

The subscribe event contains the following payload in the HTTP POST:

"type": "subscribe", 
"fired_at": "2009-03-26 21:35:57", 
"data[id]": "8a25ff1d98", 
"data[list_id]": "a6b5da1054",
"data[email]": "api@mailchimp.com", 
"data[email_type]": "html", 
"data[merges][EMAIL]": "api@mailchimp.com", 
"data[merges][FNAME]": "MailChimp", 
"data[merges][LNAME]": "API", 
"data[merges][INTERESTS]": "Group1,Group2", 
"data[ip_opt]": "10.20.10.30", 
"data[ip_signup]": "10.20.10.30"

As you can see there’s quite a bit of information here. You could take a different action depending on the list_id, for example (useful if your site has multiple lists each with its own subscriber benefits) and perhaps even sync up the interests.

To keep things simple, though, the plugin is only interested that this subscriber has been added to a list.

The subscribe function first checks to see if the subscriber email exists. If it doesn’t and new users should be created then it uses the wp_insert_user function to create a new WordPress user with the role of Subscriber from the MailChimp data.

A new user meta variable, _newsletter_subscriber, is added to the user (either newly created or pre-existing) with a value of 1. This appears as the checkbox under MailChimp Newsletter on the user profile.

Handling An Unsubscribe Event

The unsubscribe event data looks something like this:

"type": "unsubscribe", 
"fired_at": "2009-03-26 21:40:57",  
"data[action]": "unsub",
"data[reason]": "manual", 
"data[id]": "8a25ff1d98", 
"data[list_id]": "a6b5da1054",
"data[email]": "api+unsub@mailchimp.com", 
"data[email_type]": "html", 
"data[merges][EMAIL]": "api+unsub@mailchimp.com", 
"data[merges][FNAME]": "MailChimp", 
"data[merges][LNAME]": "API", 
"data[merges][INTERESTS]": "Group1,Group2", 
"data[ip_opt]": "10.20.10.30",
"data[campaign_id]": "cb398d21d2",
"data[reason]": "hard"

Again, plenty of additional information such as reason and campaign that might be useful but, for now, we are concentrating simply on the request to unsubscribe.

Like subscribe, the first action is to check for the existence of a user with a matching email address.

If one is found and we are deleting users on unsubscribe the wp-admin/includes/user.php file is included before calling the wp_delete_user function. Otherwise, the _newsletter_subscriber user meta variable is set to 0.

Displaying Subscriber Status on the User Profile

You’ll have noticed that in the subscribe and unsubscribe functions, the user meta variable _newsletter_subscriber is set to 1 and 0 according to the event.

Displaying this value is a simple matter of hooking into the show_user_profile and edit_user_profile actions to output the appropriate output. As this is read-only (we want to let MailChimp handle the events) the control is disabled.

Logging Activity

The plugin writes plenty of detail to a log file, which you’ll find invaluable when testing your own set-up.

An option in the plugin’s settings page allows you to switch logging on and off and there’s also a link to the current log file for easy viewing.

Get Hooked and Stay in Sync

That MailChimp is so popular with WordPress site owners is hardly surprising: its free plan with 12,000 emails per month enables the majority of those owners to use this industrial-strength email app for no cost.

But whilst there’s always been plenty of excellent plugins for getting your visitors to subscribe to your newsletters, aside from MailChimp Integration, the process has been something of a black hole as far as tracking those subscribes and unsubscribes in your WordPress site.

Webhooks shine a bright light into that black hole, meaning you can fairly accurately track who is a current subscriber. Not only does this potentially save a lot of tedious downloading and uploading of subscriber lists it can also open up some interesting promotional opportunities such as subscriber-only content.

]]>
http://premium.wpmudev.org/blog/mailchimp-updates-wordpress-using-webhooks/feed/ 0
The WordPress wp-config File: A Comprehensive Guide http://premium.wpmudev.org/blog/wordpress-wp-config-file-guide/ http://premium.wpmudev.org/blog/wordpress-wp-config-file-guide/#comments Thu, 11 Dec 2014 12:00:33 +0000 http://premium.wpmudev.org/blog/?p=134345 The WordPress configuration file, also known as wp-config.php, is most frequently used to set up a database connection and is then forgotten. Despite its neglected nature, it is a powerhouse of features and opportunities for optimization.

While you don’t typically use the config file on a day-to-day basis, I’m betting that almost every WordPress install could benefit from adding a couple of things to this file. A well thought out config file can not only make a website faster and more secure, it can also add features like the ability to empty the trash more frequently, or disabling features such as revisions and offer advanced debugging capabilities.

In this article we’ll look at the default settings that ship with your config file and how you can tweak it to better suit the needs of your WordPress website.

The WordPress config file

What is the wp-config.php File?

According to the WordPress Codex, the config file is One of the most important files in your WordPress installation. It file is located in your WordPress root directory and contains important information such as database connection data (username, password, etc.) and various settings.

wp-config.php is actually not a part of the files that ship with WordPress. If you download the WordPress software you won’t find this file anywhere. Instead, you’ll find wp-config-sample.php.

When you install WordPress you can rename this file to wp-config.php to set up your environment, or WordPress will create a final config file based on the information you give it during installation.

The Default Config Content

You can take a look at the default content of your config file by checking out this sample at GitHub. This is the same wp-config-sample.php file you get in your own installations. The file is extremely well documented and I’ll explain some of the settings here nonetheless.

Many settings in the config file use PHP constants. As the PHP documentation states, a constant is an identifier for a simple value. The value can not be changed for the duration of the script. The general format of a constant is define( 'CONSTANT_NAME', 'CONSTANT VALUE' ).

So let’s go through what all the code in the wp-config.php means.

Database Configuration

The first six settings are all about the database connection. WordPress stores posts and various other bits and pieces of data in a database; it needs access to said database to function. A database connection typically requires a host, a username, a password and a database name.

The code above shows the constants without the inline documentation. The first four lines define the four settings I talked about previously. The charset and collation both have to do with languages and how specific characters are stored. UTF8 is a good choice because it contains special characters like “ő” for example. Collation determines how strings are compared in the database. Some collations may be case sensitive, others may be case sensitive for example. Unless you specifically know about these things it is best to leave these two settings alone.

Salts And Keys

The next eight settings are all used for securing WordPress. Authentication keys are used as security checks while salts are used when hashing passwords.

You can fill these out yourself but there really is no need. You can use the secret key generation utility to create these constants very quickly.

I highly recommend reading Why WordPress Authentication Unique Keys and Salts Are Important – it is a great read. As the article mentions, changing your keys and salts now and again is not a bad practice. Why not set a reminder every 90 days or so?

Other Config Settings

There are two more settings in there, the table prefix and the debug setting. The table prefix tells WordPress what prefix your database tables use. The default is wp_, which would mean that your posts table is named wp_posts.

One of the best ways to protect against attacks is to be unpredictable. It is a good idea to use default settings as little as possible, especially when they pertain to something as crucial as your database. If you’re just installing WordPress it’s a good idea to use an obscure prefix such as Jbh8h3dD_oj3e_. WordPress won’t mind that this is a lot more complex; to a script there is very little difference between wp_postmeta and Jbh8h3dD_oj3e_postmeta.

The next setting is all about debugging WordPress. By default it is set to false, which means that error messages will be hidden. This is desirable behavior on production websites, but while coding or debugging you definitely want to see errors so you can fix them. If you ever activate a theme or a plugin and get a white screen you can at least figure out what the issue is by setting the WP_DEBUG constant to “True.”

Customizing the wp-config File

The config file is just like any other file, which means you can add any valid PHP to it. That being said, you should take care when editing wp-config.php. Only add to it when absolutely necessary and take care when editing because any incorrect edits you make could cause your website to stop functioning. After all, this is the heart of WordPress we’re tinkering with!

It’s a good idea to refer to the wp-config documentation in the WordPress Codex for all the official tweaks you can make to this file. All the additions I’ll be mentioning in this article are safe to use if pasted correctly, but please be aware of what each of them does.

There are some edits that you can make which have a place in the config file but are not a part of the documentation. One good example of this is the API access key and secret for your Amazon S3 server when using the Amazon S3 and Cloudfront plugin. You could also use it to store your Google Fonts or Google Maps API key and other similar things.

Do keep in mind though that this method is not for every single bit of data around. If you’re creating a plugin where the user needs to enter his/her address it should be stored in the database.

1. WordPress URLs

There are two settings you can set in the config file which control WordPress URLs. One is the WP_HOME constant and the other is the WP_SITEURL constant. There is always some confusion about these, so let’s clear things up.

WordPress URL boxes

Both settings can be controlled from the WordPress settings section in the admin. The first setting in the screenshot, the WordPress address, corresponds to WP_HOMEThe second setting, site address, corresponds to WP_SITEURL.

When you use the config file to define these URLs, the settings given in the admin are overwritten and the config file takes precedence.

The WordPress address, or WP_HOME, is the URL that users enter to visit your website. The site address or WP_SITEURL should point to the root of your WordPress install, which could be in a sub-directory.

To learn more about the use and issues with these URLs I suggest reading Using WP_SITEURL and WP_HOME to migrate a WordPress site.

2. Custom Directory Locations

The config file allows you to modify the location of various folders used by WordPress. You can move the content, plugins and uploads directories and create additional theme directories using the method outlined below. There are three reasons you may want to do this:

  • Mimicking a folder structure following a site migration from another system
  • Additional security based on not relying on the default structure
  • Clearing up clutter from the root directory

Note that different folders behave slightly differently. The wp-content folder requires an absolute path and a full URI to be given. The plugins directory is much the same, but for compatibility issues you may want to use the PLUGINDIR constant as well.

Themes and uploads are a bit different. The default theme directory is hardcoded into WordPress, it is always set to the directory named themes inside the content directory. You can, however, add additional theme directories. In the code above I created a theme directory in the root folder.

The uploads directory is always relative to the ABSPATH directory, which would be your root directory. In this case I have placed the directory in the root folder.

Assuming WordPress is in a wordpress sub-directory the code above would result in the following folder structure:

WordPress folder structure
Original WP folder structure on the left, custom structure on the right

There is a special kind of plugin folder not many people know of called mu-plugins, short for “Must-use Plugins.” These plugins are loaded by default before any other plugins. To learn more about them ready the Must Use Plugins documentation in the Codex. If you like the idea but want to change the location you can do so in a similar fashion to how we changed the plugin directory above.

3. Custom Default Theme

The default theme in WordPress is the most recent twenty-something theme. In WordPress 4.0 this would be Twenty Fourteen. If you would like a different fallback theme you can change the WP_DEFAULT_THEME to the folder name of your preferred theme.

If you must change this I advise choosing a simple but very well-coded theme. If something goes wrong and your site’s theme is missing it will revert back to the default theme.

Custom Database Tables

WordPress has the ability to use a different table name for the users and usermeta tables. Using a custom table name could give you some additional protection although it is highly probably that if someone has access to your database they will figure this one out.

Before you make the change be sure to read up on changing user tables to make the transition as smooth as possible.

4. Revisions, Autosaves And Trash

I’m betting that many WordPress users don’t use the post revisions feature. Even though it has been around since WordPress 2.6 it’s use is relegated to niche corners of the web. Luckily, WordPress allows you to limit or disable revisions easily using the WP_POST_REVISIONS constant.

Note that you should only use one or the other, I’ve just placed both in one example for easy reference.

The use of autosaves are more widespread but these may happen a bit more frequently than you need them to. By default WordPress saves your post every 60 seconds. If you create content by copy-pasting it, or you’re not worried about loosing a minute’s worth of work you could increase the autosave time.

The trash is another source of clutter which can be controlled easily. By setting the EMPTY_TRASH_DAYS constant you can control how many days a post stays in trash before it is completely deleted. You may also set this to 0 to disable the trash altogether.

5. WordPress Multisite

The config file is the starting place for creating a multisite install. The Create a Network page in the Codex sums up what a Multisite installation actually is:

A multisite network is a collection of sites that all share the same WordPress installation. They can also share plugins and themes. The individual sites in the network are virtual sites in the sense that they do not have their own directories on your server, although they do have separate directories for media uploads within the shared installation, and they do have separate tables in the database.

Multisite allows you to create separate sites based on the same WordPress install. This allows you to manage a multitude of sites very easily. Multisite is commonly used for corporate websites where the shop, blog and company site may be separate. It could also be used to host websites for a community of bloggers. Developers use it to host multiple themes and plugins.

To get started you’ll need to define a single constant:

Once defined, reload the WordPress admin and you should see a “Network Setup” option in the “Tools” section. Follow the instructions outlined there. WordPress will ask you to add additional settings to your config file as well as your .htaccess file. Once done you should be logged out and when you log back in you’ll have a nice new network install. Refer to the Create A Network page for a more complete setup guide.

A setting related to Multisite installs allow you to redirect users when someone accesses a sub-site, which does not exist. The NOBLOGREDIRECT constant defines the URL users are directed to in these cases.

Especially when working with Multisite installations you may want to make sure that plugins and themes cannot be edited using the built-in file editor, you may even want to make sure users can’t install their own plugins and themes. This can be achieved with the DISALLOW_FILE_EDIT and DISALLOW_FILE_MODS constant.

Note that if you define DISALLOW_FILE_MODS as true you don’t need to define DISALLOW_FILE_EDIT since this will be disabled as well.

6. Developer Settings

The config file has a number of settings which help developers catch errors or write better code. The most prominent of these is the WP_DEBUG constant, which we’ve already look at. Defining this as “True” will force errors to be displayed.

In addition you can make sure that the full and unmodified CSS and Javascript files are served on a page load:

By default, scripts are concatenated and minified. Concatenation is the process of joining files. Instead of loading 20 scripts individually WordPress concatenates them into one file and loads that. Minification is the process of compressing a file into a format which is non human-readable but computers work just fine with it. These two methods save considerable loading time and server resources.

That said, it is next to impossible to figure out a Javascript or CSS issue if the code is concatenated and minified. Using the two constants above to disable these features is necessary if you need to hunt down a script issue.

Debugging often relies on log files, especially if errors are not shown. Many errors only occur in specific circumstances so as a developer we don’t always encounter them. This is where logging comes in handy. Instead of displaying error messages we can log them to a file and look over them every now and again. This can be done by defining WP_DEBUG_LOG:

When enabled the errors encountered will be logged to a file named error.log in the wp-content folder.

For the hardcore optimizers among us, the SAVEQUERIES constant is a life-saver. By defining this constant to be true we can access detailed profiles of the SQL queries performed by WordPress:

Once defined we can print the content of $wpdb->queries to get an overview of all the queries.

If you’re feeling particularly fancy or you need to look at these queries all the time you can hook this into wp_footer to make sure they are always displayed at the end of each page.

7. Increasing The Memory Limit

In some rare cases you may need to manually allot more memory to WordPress. While I have encountered situations where PHP ran out of memory while running WordPress, these were all caused by wasteful themes or plugins.

If you need to you can set the memory limit with the WP_MEMORY_LIMIT constant and the WP_MAX_MEMORY_LIMIT constant, which controls the amount of memory available for the admin.

8. Cron Settings

Cron is a time-based job scheduler in Unix-like environments. WordPress has a cron feature, which is not a real cron but copies its features closely. WordPress cronjobs run at regular intervals and perform various tasks. For example, the cron system is responsible for publishing posts at the correct time.

The drawback of the system is that it relies on site visitors to perform cronjobs so the task may not run at the exact given time. If you set a real cron on your server to run at 1am every night it will do so with extreme precision.

WordPress crons are triggered by visitors loading the site. This means that if you use WP cron to initiate an action at 1am it will be run the first time the website is loaded after that time. If you don’t have any visitors until 11am, the task will be completed then.

In most cases this is not a problem. If you’ve set a post to be published at 1am and noone visits the site until 11am the post will be published before the site loads for the user, for all intents and purposes, the post was published on time.

In some cases the cron system may throw a fit and refuse to work properly. I have never personally encountered this, but if you see this happening you can try using an alternative cron method:

The config file also allows you to disable the cron altogether and to limit the repeat interval between the same cronjob.

9. Disabling Table Updates

When WordPress is updated it may run a dbDelta() function, the purpose of which is to modify your database to conform to the latest specifications. This usually poses no threat at all but for sites with huge tables (especially username tables) this may take a while to complete.

Many large sites prefer to take care of these operations themselves, or perhaps schedule them for a time when there is little traffic. This can be done by disabling the upgrading of global tables:

10. SSL In The Admin

There are two options in the wp-config.php file which allow you to use SSL. FORCE_SSL_LOGIN makes sure that logins always use SSL, but the admin sessions themselves don’t. This adds some protection while making sure SSL doesn’t slow down the admin process.

You can also use FORCE_SSL_ADMIN, which will use SSL for login and throughout the admin session, including the cookies:

FORCE_SSL_ADMIN supersedes FORCE_SSL_LOGIN, so if you’re using the more secure option there’s no need to define FORCE_SSL_LOGIN.

Depending on your server setup there may be a bit more you need to do to access your site via SSL. I suggest reading the excellent Administration Over SSL guide in the Codex.

11. Disable Automatic Updates

I personally enjoy automatic updates because they make my website safer and ensure I’m always running the latest version of WordPress. Being always up-to-date is a good thing and there are very few legitimate cases where not updating is a good idea. Modifying WordPress core files, a downloaded theme or plugin is never one of them.

If you need to disable updates for any reason, WordPress gives you two constants to do so. AUTOMATIC_UPDATER_DISABLED can disable all automatic updates in one go. A better way to do this is to use the WP_AUTO_UPDATE_CORE constant.

This can be set to “True” to enable updates and “False” to disable them. In addition, you can set it to “Minor” (this is the default) to grab minor updates by default:

Conclusion

As you can see, the WordPress configuration file offers plenty of opportunities to tweak your site and make it your own. From modifying directory locations to logging in via SSL, a lot is possible.

What are your favourite wp-config.php tricks, did I miss anything or do you use something which isn’t official but works great? Let us know in the comments below.

]]>
http://premium.wpmudev.org/blog/wordpress-wp-config-file-guide/feed/ 11
How to Use AJAX in WordPress to Load Search Results http://premium.wpmudev.org/blog/how-to-use-ajax-in-wordpress-to-load-search-results/ http://premium.wpmudev.org/blog/how-to-use-ajax-in-wordpress-to-load-search-results/#comments Mon, 08 Dec 2014 13:00:23 +0000 http://premium.wpmudev.org/blog/?p=134394 AJAX is a very powerful and flexible tool that allows developers to create more streamlined applications. It can be used for a wide range of purposes such as loading content or verifying login credentials. The main benefit of AJAX is that it is asynchronous, meaning the whole page doesn’t need to reload in order for it to receive new data.

WordPress is well-equipped for AJAX. It has a great mechanism for working with it, allowing you to implement AJAX functionality with little fuss.

In this article I’ll take you through the basics of AJAX and we’ll create a very simple extension that pulls in search results using AJAX in the default Twenty Fourteen theme.

AJAX
Making the most of AJAX with WordPress.

What Is AJAX?

AJAX is actually not one technology, it is a mixture of programming languages you probably already know. AJAX is short for Asynchronous Javascript And XML. Javascript is used to send some data to the server, which spits back something in return in XML format.

XML is actually not necessary, JSON is frequently used instead. When JSON is used we sometimes refer to it as AJAJ instead of AJAX. In fact, since a simple string or HTML could be returned by the server, we don’t need to be restricted to XML or JSON at all. For the purposes of this article I will refer to AJAX regardless of the type of data we return.

How is AJAX Used?

Let’s look at a practical example without delving into code. Let’s say you’ve created a real estate website and you offer the opportunity for visitors to save a listing to view later. This functionality could be offered using a “Save For Later” button.

When a user clicks this button they are taken to a script which adds the listing to their later list, and they are redirected back to the page they were viewing. This means that the page needs to be loaded again. A real estate website could be very image-heavy and many images may not be cached, which would contribute to a longer loading time.

A much better solution would be the following: The user clicks the button and a little loading animation is shown on the button. The button then fades out, the text “Listing Saved” is shown in its place. While this is happening the user can continue to use the website as usual.

Under the hood the process is very similar in both cases. When the button is clicked the user is not taken anywhere, but using Javascript we make a request to a specific file, providing the listing ID. The file in question figures out who the current user is and using the provided listing ID adds it to their later list. Once this is done the script returns a value which is transported back to the Javascript function. Based on this we can manipulate the UI to show the user meaningful interaction messages.

Don’t worry if that seemed a bit complex! In practice the process is pretty easy, it just takes some getting used to.

Using AJAX in WordPress

AJAX is completely independent of frameworks such as WordPress. You could implement it any way you like. There is, however, built in support in WordPress for an AJAX workflow. You should follow this if you want your plugin or theme to pass muster.

Let’s look at a very simple example in three steps. We’ll go from a custom solution to using AJAX foundations in WordPress without actually using AJAX itself to a fully-fledged implementation. We’ll create a one-time button, which will be displayed if the user hasn’t clicked it yet, or it will show “already clicked” if the user has clicked it before.

Custom Implementation

Before we continue we need to figure out how we know if a user has clicked the button or not. If a user clicks the button we will create a clicked_link user meta with the value of “Yes.” Here’s a function which checks this for us:

Now we can create the user interface. The button will show up if the user hasn’t clicked it yet (it will only be visible to logged in users). If a user has clicked it, the text “Already clicked” will be displayed:

When a user clicks the button the page is re-loaded with the button_click query string. Based on this value we can use an action to set the user meta:

Note that this method is not recommended for a number of reasons but it serves as proof of concept. At this point the button will show up for logged in users who have not clicked it. When you click it you are re-directed to the same page. Well before the button is loaded the user meta is recorded and as a result the correct “Already clicked” text is shown.

AJAX Foundations Without AJAX

Let’s bring this example one step closer to an AJAX implementation. We can already utilize the functions WordPress offers without actually writing any Javascript. This involves routing our actions through admin-ajax.php. Let’s take a look at how the code for our button changes as a result:

The only change is in the button’s URL. It points to the admin-ajax.php file in the WordPress admin directory. Additionally, an action parameter is specified with the value of button_click. We can’t write functions to deal with our actions into this file since it is a WordPress core file. We can, however, use actions to tie them to these events.

In order to tie a function to an action in the admin-ajax.php file we need to use the wp_ajax_[action] or wp_ajax_nopriv_[action] hooks. The former is fired for logged in users only, the latter for logged out users only. This is already a great way to protect our scripts!

Note that I also re-wrote the user_clicked() function to facilitate the changes. We no longer need to check if the user is logged in since that is taken care of by the wp_ajax_button_click hook. We do need to redirect the user back to the previous page, though.

Full AJAX Implementation

Our full AJAX implementation will use the foundations we’ve built in the previous example. Let’s begin by writing some Javascript, which will handle the click event on the button.

We detect the button click and use the ajax() function to send a request to the admin-ajax.php file. We make sure that the request type is post and the action is given as well. Elements of the data object will be transported as members of the $_POST array. A success function is put into place, which will replace the button with the already clicked text if the response is “OK.”

Note that from the admin-ajax.php file’s point of view this request is much the same as when we sent our users to the file directly. The action is set and thus our hook from before will function in the same way.

This time we don’t need to redirect the user since they won’t leave the page in the first place. We do need to echo “OK,” which will be used by our success function and we need to die(). This is required because the admin-ajax.php file will echo “0” otherwise.

Once a user clicks a button everything is handled asynchronously. Users can continue to use the site while this action is taking place. The button will eventually (pretty quickly) be replaced by the clicked text. If the user re-loads the page they will not see the button again since they have already clicked it.

AJAX Implementation With Fallback

Our new AJAX method is awesome but will ultimately fail if a user doesn’t have Javascript enabled. To be fair, it will work, but it won’t redirect the user back to the page they were on since we echo “0” and then die. WordPress provides the DOING_AJAX constant, which we can use to determine if an AJAX request is happening. If it is we echo and die, if it isn’t then we redirect:

By using this method we can use the same functions and same workflow for handling situations where Javascript is enabled and situations when it isn’t.

Load Your Site’s Search Results With AJAX

Let’s modify the Twenty Fourteen theme to load search results using AJAX on the search page. The first step is to create a child theme. Take a look at our artist on how to Create WordPress Child Themes for more infomation.

Enqueueing Assets

Next, let’s enqueue the javascript file we will use to implement our Javascript functionality. Note that I will make sure that the script is only loaded on the search page. The reason for this is that the search page may have a different sidebar than the regular post list page. So when the user first searches, the search page will actually load. Once on the search page the results will be pulled in via AJAX.

I have used the wp_localize_script() function to make sure I have access to the location of our admin-ajax.php file. Previously, this could be retrieved from the URL of our button, but we have no way to grab it from the page here.

The wp_localize_script() function can be used to add language support to your scripts. It is also a great way to pass variables to it as well which is how I’ve used it here. This will allow us to use myAjax.ajaxurl to point to the correct URL in our Javascript.

I’ve also enqueued a CSS file. The minimal CSS code we’ll be using could very-well be added in the child theme’s stylesheet. I chose to enqueue a dedicated file simply to compartmentalize our assets, it makes it easier to create a plugin out of it in the end.

Intercepting Searches

The next step is to intercept searches, stop them in their tracks and pass the search query to our custom script, which will return the new results. Let’s set up the Javascript for that now:

I used the beforeSend event to add a loading class to the content element and to disable the input. This will give the user some feedback and make sure that multiple searches don’t lead to multiple requests being sent. Upon success the contents of the #content element is replaced with the new results.

The CSS we’ll use to handle loading is the following, which will fade the content and produce a nice loading overlay:

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

Loading Posts With AJAX
Loading Posts With AJAX

The Server Side

Our action from our Javascript call was load_search_results. We’ll need to use this in the actions we’ll be creating. This time we’ll need to make sure that it runs for both logged in and logged out users so we’ll be using both wp_ajax and wp_ajax_nopriv.

We’ll create a custom WordPress query and use the exact same code found in search.php in Twenty Fourteen to return our results:

The result of this function is some HTML, which is created using functions native to WordPress and Twenty Fourteen. This ensures that we’ll get the correct format every time, even if there are no posts found.

Conclusion

From small UI improvements to larger scale performance increases, AJAX is a great addition to your WordPress toolkit. When you encounter it for the first time you may need to try it out to wrap your head around it, but it really is very simple. It’s the complexity which can be added by complex Javascript on the front-end and complex PHP on the server side, which sometimes makes it a bit more difficult, not AJAX itself.

If you’re interested in AJAX functionality I highly recommend browsing through the AJAX-related plugins available in the WordPress Plugin Repository. I also suggest reading the W3Schools AJAX Tutorial and the documentation for the jQuery Ajax Function.

If you’ve created something great using AJAX in WordPress or you feel that some aspects of WordPress would benefit a lot from adding some AJAX at them, let us know in the comments below.

]]>
http://premium.wpmudev.org/blog/how-to-use-ajax-in-wordpress-to-load-search-results/feed/ 4
How to Organize and Declutter the WordPress Post Editor Using Tabs http://premium.wpmudev.org/blog/organize-wordpress-post-editor-using-tabs/ http://premium.wpmudev.org/blog/organize-wordpress-post-editor-using-tabs/#comments Sun, 07 Dec 2014 13:00:06 +0000 http://premium.wpmudev.org/blog/?p=134636 Even on a fresh installation of WordPress, the post editor screen can appear a little cluttered thanks to the meta boxes displayed alongside and below the main content editor.

While they are useful – allowing you to do things like choose a post category, add tags and set a featured image – they can make it difficult to find what you are looking for or focus on the task at hand when various meta boxes are crowding the screen.

By the time you’ve installed a few essential plugins for things like search engine optimization and promoting your content online, the post editor screen can start to look very cluttered indeed, and can even become overwhelming for new WordPress users.

While you can choose to not show these meta boxes from the screen options settings, simply hiding them from sight isn’t the ideal solution if you want to continue to make use of them.

To help you streamline the post editor screen and make it less distracting, we’re going to look at a free plugin solution that makes the most of tabs in today’s Weekend WordPress Project.

Weekend WordPress Project

Organizing Your Meta Boxes With Tabify Edit Screen

Tabify Edit Screen is a free plugin that gives you more control over how the post editor screen is organized. The plugin achieves this by allowing you to use tabs to separate the different meta boxes that are active on your WordPress website.

An Example Meta Box

With Tabify installed on your site, it’s now possible to create custom tabbed layouts for the post editor screen for each post type on your site. This includes pages and any custom post types you are using.

Conveniently, Tabify is compatible with meta boxes added by other plugins, such as the JM Twitter Cards plugin or WPML. However, with some plugins the meta boxes are lumped together under the custom fields option, and therefore can’t be separated out into their own tabs.

Meta Boxes from Plugins

Once the plugin has been installed and activated on your site, its functionality can be accessed from Tabify’s settings, which can be accessed from the left-hand sidebar of the WordPress admin.

Creating Tabs

From the Tabify edit screen you can enable tabs for different post types. For each post type that you enable tabs for will have its own set of tabs.

Each post type can have multiple tabs as needed, and you can name the individual tabs before moving them into position.

Tabify Edit Screen Settings

After checking the option to show tabs for a particular post type, you can click on “Create a new tab” to get started.

Create a New Tab

Giving your tabs a meaningful name will make it easier for you and any contributors you may have on your site to determine which set of meta boxes will display under a particular tab.

Organizing the Meta Boxes

Once you’ve created at least one new tab, you can then drag and drop the available meta boxes onto the appropriate tab area to start reorganizing the post editor screen and decluttering the WordPress workspace.

New Tab Arrangement

Once you’ve finished, or you want to preview your progress, click Save Changes and then open up the Add New Post page to view the editor screen.

Example Tab Arrangement

When switching tabs, you will notice that the post title and Publish meta boxes are displayed under each tab, making it easy to see the status of your post and its title.

New and Improved Post Editor Screen

If you would like to edit your configuration, you can switch back to the Tabify edit screen and make your changes. If you activate any additional meta boxes on your site via any plugins you install they will be automatically added to the last tab in the editor. So if any new meta boxes are added to your site, remember to return to the settings page to move them under the appropriate tab.

Conclusion

Tabify Edit Screen provides an easy way to better organize the WordPress editor screens. If you are fed up of scrolling up and down the page in search of a particular meta box then spending a few minutes setting up tabs could save you a lot of frustration.

It would be nice if you could apply the same tab configuration to multiple or all post types on your site rather than having to create each one individually. However, if you mainly work with the default WordPress post type this shouldn’t be an issue.

If you multiple people are working on your site, it might be worth mentioning that you are using tabs on the post editor screens in your style guide or writer instructions, just so that they know where to find any reorganized meta boxes.

If you have any questions about using this plugin or more tips for improving the WordPress post editor screen, please leave a comment below.

]]>
http://premium.wpmudev.org/blog/organize-wordpress-post-editor-using-tabs/feed/ 2
Avoiding Common WordPress Image Issues http://premium.wpmudev.org/blog/avoiding-common-wordpress-image-issues/ http://premium.wpmudev.org/blog/avoiding-common-wordpress-image-issues/#comments Sat, 06 Dec 2014 13:00:51 +0000 http://premium.wpmudev.org/blog/?p=134895 For artists and photographers, WordPress is an ideal platform for showcasing the beauty of your work to the rest of the world. The only problem is, if you don’t know what you’re doing, it’s easy to make mistakes that can leave visitors to your website less than impressed.

I’m talking about using the wrong themes and plugins, and neglecting to optimize your images.

So in this post we’re going to look at the three most common mistakes you’ll find on image-heavy sites and how to avoid them.

WordPress image issues.
Fix your WordPress image issues.

1. Feature-Packed Themes

How could a theme be bad when it has a ton of built-in features? Because it has a ton of built-in features.

A feature-packed theme might not seem like such a bad thing… until you try to switch themes. Only then will you discover your once functional site has been stripped of its content.

When features such as galleries and portfolios are hard-coded into a theme, it prevents big issues if you decide to switch themes. Let me explain.

Let’s say you buy and install a theme that has a beautiful gallery built in, along with sliders, carousels, and a ton more awesome features. Then after a time you decide to change your theme because you want to update its look and feel. So you buy a new theme and it looks fantastic. It’s just what you were looking for and you install and activate it. Then you check out the front page of your site… and everything’s a mess. All you see are shortcodes and, even worse, error codes. Where are all your pictures, galleries and sliders? They left with your old theme. Oops.

After deactivating a theme with built-in features, a bunch of excess code will be left on your page

Because those features were built into your theme, switching to another theme means those features will disappear because they are not likely part of your new theme.

Now you’re left with a big mess to clean up.

The Alternative

The best possible solution is to get your hands on a simple, clean theme and use plugins to add any functionality you need. This would allow you to easily switch themes, while your plugins would take care of your galleries, portfolios, sliders, and any other features on your site.

The Fix

Theme features
If you’ve ever visited ThemeForest, you’ll be familiar with themes that offer a gazillion features.

If you’ve switched from a feature-packed theme to a well, not-so-feature-packed theme, all of your content will still be saved in your database. Unless you want to do a lot of coding, and possibly replicate the features you had in your old theme in your new theme, it can be tricky to proceed. So before you do anything, back up your database and all your site’s files.

Once everything’s backed up, reactivate your old theme and simply removing the content that uses the features of your theme. Every theme is different, but you may find a button that will disable the added features, or you can otherwise remove them.

Sometimes this means going to each page and removing a shortcode or two. Other times this may require going to your widgets page and removing the widgets from your sidebar (if you use one).

Extra Tip: You can inform your visitors of the improvements you’re making, while also letting them know you’ll be back soon so they don’t lose interest during your refurbishing process. If you create a simple page with your logo, or site name, and a short message explaining that you’re refurbishing your space, you can add it as your static home page.

Go to Settings > Reading, and select the “a static page (select below)” under the first heading, “front page displays.” Now select the name of the page you just created under “front page” in the select box, then save your changes.

Now you can make all the changes you want and your visitors will only see your message instead of a broken site, know what’s going on, and will know they can return soon.

It might seem like a pain, but it’s a lot easier than deleting what could possibly be miles worth of coding, or shortcodes from every page and sidebar. You’ll have to filter through the codes to find the snippets of actual text, and that can take days.

If you remove those features straight away with a few clicks, it will eliminate hours of work later on.

2. Overly Complicated Plugins

Similar to feature-packed themes, bloated plugins can weigh down your site immensely. Sometimes badly-coded plugins can introduce a whole whack of new code rather than using WordPress best practice.

If you decide to delete the inefficient plugin and replace it with a better one, you may see a block of code leftover from the old plugin. Again, it’s annoying to have to edit out.

Sometimes there will be an option to remove and delete all the plugin’s content when you delete the plugin. If the options is available, simply remove the content manually while the plugin is still active. After the content is removed, you can disable and delete the plugin without issue. Don’t forget to back up your database and site files beforehand.

Beyond this, there’s an even more serious issue. Inefficient plugins may cause your site to operate incredibly slowly. And considering your website is probably image-heavy, the last thing you want to do is keep visitors to your site waiting while image load.

With both of these at play, your site can be incredibly backed up and slow as the dickens. It’s really not worth it, even if the features are amazing. What’s the point of them if your visitors can’t even load your website?

The Alternative

If you can find plugins that don’t re-invent the wheel, and use WordPress’s natural assets, all the better. For example, if you want to display a photo gallery on your site, it’s best to use plugins that make the most of the built-in WordPress gallery feature. A great plugin I would recommend is PhotoPress – Gallery.

The PhotoPress Gallery plugin for WordPress

3. Neglecting to Optimize Images

No doubt you want to put your best foot forward with captivating images. The only problem is, large files can really weight down your site, which is why it’s important to optimize your images and reduce their file size.

You may already have a plugin to optimize your images, and you might even think this point is, well, pointless. However, how well does your plugin really work?

There are a lot of plugins that promise to optimize your images, thus, saving some much-needed space on your server, but do they really do a good enough job? I’ve downloaded and installed many image optimizing plugins, only to delete them two minutes later.

It was incredibly frustrating to download these plugins (and sometimes buy them, too), only to discover my large images were “optimized” by reducing the file size by 1 kilobyte. Seriously! Only 1 measly kilobyte.

The Alternative

Luckily, I have found a plugin that’s hugely efficient and isn’t bulky. It’s our very own Smush.it. So many people have appreciated this plugin for a long time, even after it changed hands. We’ve worked on this plugin to make this plugin even better.

WP Smush.it
Smush your images with WP Smush.it or WP Smush Pro.

If you want even more “smushing” power, check out our new WP Smush Pro plugin. It allows you to smush images more than 1MB in size.

No matter which plugin you decide to use, be sure to take it for a test run before relying on it too heavily. Monitor your server while you optimize images when testing out your desired plugin.

You’ll be able to see how many resources the plugin is using and decide whether or not it’s efficient for your site. It’s also a good idea to compare the data you collect with other image optimizing plugins you test out. This way, you can find the absolute best one for you.

This may not always be possible since you’ll have to pay for a lot of them. Usually, there will be a free version of the paid plugin that you can test out. The free version will be a fairly good indicator of what you can expect from the paid version.

Summing Up

When you’re an artist first, putting together a website can be a big task. You will likely find resources that promise many great features specifically for you, but may end up causing you problems in the long run.

If you’re picking a theme or plugin with built-in features, you may run into problems if you decide not to use them anymore. Removing them can cause unexpected compatibility issues, as can keeping them if updates render them incompatible. They may even end up slowing down your site tremendously.

It’s best to search for clean, simple themes and customize them as much as you like to get your desired look and feel. This also includes finding light-weight plugins to offer the features you desire. Similarly, it’s important to find an efficient image optimizing plugin to help reduce the clutter.

Have you found any awesome, light-weight, and efficient plugins for your site that I haven’t mentioned? Share them in the comments below.

Image credit: William Murphy, and Peter Adams.

]]>
http://premium.wpmudev.org/blog/avoiding-common-wordpress-image-issues/feed/ 0
Learning PHP for WordPress Development: A Comprehensive Guide http://premium.wpmudev.org/blog/getting-started-with-wordpress-development/ http://premium.wpmudev.org/blog/getting-started-with-wordpress-development/#comments Tue, 02 Dec 2014 13:00:00 +0000 http://premium.wpmudev.org/blog/?p=134062 So you have a WordPress website and you’ve tweaked your theme, read a bit about template tags, and perhaps even modified your functions.php file in the built-in theme editor.

And now you want to it your skills to the next level and delve into more code.

Luckily, WordPress is a great place to start. There is a truckload of documentation available and the code is – for the most part – easily readable, self explanatory and not too difficult to remember.

In this article, I’ll give you a brief introduction to the world of WordPress programming. While this post is aimed at beginners, it does presume you’ve tinkered with WordPress before and you know basic HTML. I will assume that you know how to edit WordPress files and you’ve looked into a WordPress theme file – even if you didn’t understand what’s going on.

WordPress PHP
Level up your WordPress skills and tackle some PHP.

The Programming Languages Of WordPress

WordPress uses a number of different programming languages. If one language has to be singled out as the “main” one it would be PHP. PHP is a server side language, which powers about 82 percent of the web.

WordPress also uses HTML, CSS and Javascript. HTML is used to give your website structure and is employed by all websites. CSS helps style your HTML structure. CSS makes your background white, your text dark-grey and positions the sidebar on the right. Javascript adds advanced features like sliders and other interactive features.

Finally, WordPress also uses MySQL, which is responsible for querying the database. MySQL is used to retrieve the last 10 posts, or all posts in a particular category from the database.

OK, so the bad news is that this is a considerable body of knowledge. The good news is that you don’t need to know everything to get started; in fact, you can get by with very little. I myself learned programming through WordPress about eight years ago by just copy-pasting examples from the documentation.

A Note From Someone Who’s Been Through It All

As I mentioned, I learned through tutorials, documentation, the work of others – I’ve been where you are now, and I went through all the phases you will. The difficulty with programming does not come from the complexity of the languages involved. When broken down into components, everything you learn is easy.

I find that programming is hard for two reasons. You need to know a lot of simple things and in order to create a successful product you need to be able to think in terms of systems, which takes a bit of practice.

What I wanted to make sure you know is that while learning to code for WordPress you will have plenty of #$#%!! moments. You will be frustrated with your lack of understanding early on, what you think is perfectly formed code won’t work, you’ll spend hours battling with it only to discover you’ve forgotten a semicolon. This is all perfectly normal. Every single successful programmer has felt this, it’s not just you. I promise that if you keep at it, you’ll be able to code a theme in no time.

What WordPress is Not

It is important to realize that technically there is no such thing as “WordPress coding” and “WordPress code.” WordPress is a bunch of code written in PHP. Joomla and Drupal (two other content management systems) are also written in PHP.

Analogy to the rescue! Saying “WordPress code” is like saying “BMW Car.” A BMW, a Jaguar and a Nissan are all cars – they are all built with nuts, bolts and welding. The difference between them is how they are put together, the design philosophies and the assemblage practices.

WordPress, Joomla, Drupal and all the other systems and frameworks out there are all built with the same components. The difference between them is the coding philosophy and methodologies they employ.

How PHP Works

As I mentioned earlier, PHP is a server-side scripting language. In contrast, HTML is a client-side language. Let’s analyze HTML first to understand what this means.

The way your browser interprets HTML code is the following: When you visit an HTML page the HTML code is sent to your browser. Your browser processes the information and spits out something you recognize as a web page.

When your browser visits a page that employs PHP, an intermediate step is employed. First the PHP code is processed by the server. The result of this processing is an HTML page, which is then sent to your browser and displayed to you.

The additional processing by the server seems like an unnecessary step but far from it. Let’s look at a practical example with real PHP code:

Without any understanding of PHP code, we can already gather some information about it. Just by reading it you can discern that if a particular set of circumstances is true we display “Good night,” otherwise we display “good day.”

When you look at the source of the resulting web page there will be no trace of this code. All you will see is either “Good day” or “Good night.” This is because the server does the processing and only sends you the result.

In the example above I used the date function to determine what time it is. date( 'G' ) returns a number from 0 to 23 where 0 represents midnight and 23 represents 11pm. If the value of this function is more than 18 (it is later than 6pm) we display good night. Otherwise we display good day.

Now we know two things about PHP! It allows us to use if statements to display content based on our own criteria. We also know that it has functions, which help us out. The date() function returns the current date in a given format. The strtolower() function will turn any text to lower-case. A number of these functions empower you to do great things with PHP.

PHP in WordPress

With that last paragraph in mind, you can recognize PHP everywhere in WordPress. Let’s open the content.php from the Twenty Fourteen default theme and take a look. This file is responsible for displaying the content of blog posts in the theme.

Let’s compare the first line of this file (discarding the comment on top)…

…with the output it generates when you visit the page:

We can deduce from the comparison that the the_ID() function is replaced by the ID of the post in question. The post_class() function adds a lot of classes to the HTML element. These help us in styling our posts later on. It’s not important at this stage to know why these specific classes are added, we’re just familiarizing ourselves with functions.

Further on, looking at lines 24 through 28 we can also see an if statement at work:

The if statement has is_single() in it. This is a function which will be true if we are looking at a single post page, otherwise it will be false. If it is true and we are on a single page, we use the the_title() function to output the title.

If it is false, we still use the the_title() function, but we make sure it is a link to the single post page.

Notice that some functions are “empty” while some have bits and pieces within them. For example, is_single() is an empty function while the_title() has some gunk within the parenthesis.

The items within the parenthesis are called arguments. Each function has different arguments separated by commas, which you can learn about through documentation. The Codex article on the_title() shows us that this function has three arguments:

  • The first argument allows us to add HTML before the title,
  • The second allows us to add HTML after the title, and
  • The third parameter determines weather the title is shown (echoed) or it is just stored for use later.

Based on this, we now understand what’s going on in line 25 of the content.php file:

The function shows the title but we prepend an H1 starting tag to it and append the end tag.

The result of this code looks like this in the browser:

How to Level Up in WordPress Programming

Chances are you don’t want to spend weeks wading through PHP documentation and learning about everything from the ground up. You should do this, but I also recommend you experiment as much as possible.

Want to move the list of tags from the bottom of the article to the top? The the_tags() function at the bottom of the content.php file looks promising.

First, let’s delete it together. Then, when you save and refresh the page, the tag list if gone. This is great, it means that this is indeed the function that outputs the tags. Now just copy it and paste it in to various parts of the file to see where it ends up.

it is probable that the higher up you go in the code, the higher up it will be in the article. With some experience you’ll be able to identify things like the_excerpt() and the_content() being responsible for displaying the content, so putting it anywhere above those will place it above the main content.

Learning how to code for WordPress this way is fun and encourages you to read the documentation, which is always a good thing. Don’t worry if you don’t understand everything – you will reach a point when you do soon enough.

Learning Bad Practices

One drawback of this method is that you will employ bad practices. While my recommendation that you copy-paste the the_tags() function to the top of the file somewhere works, the HTML for the footer, which uses the footer tag, will need some modification to make it good code.

Again, forget about this for now. You are not building professional-grade production-ready code for Google. You are trying to learn the basics and figure out how everything works. This is not an easy task and mistakes are part of the process.

Once you have a good working knowledge of the code behind WordPress, you can start un-learning your bad practices and you can start studying coding patterns and figuring out why we do things the way we do.

An Overview Of Important WordPress Code

WordPress has a number of “subsystems” such as the loop which controls the posts shown, hooks which allow you to modify default functionality, various APIs and of course themes and plugins. I’ll give a brief introduction to some of the bigger systems you may encounter.

Enabling Debugging

By default, WordPress will hide any code errors. This is desirable in a production environment but can lead to two issues while developing. If you make a non-fatal error you won’t get any error messages and your code either won’t do anything or won’t produce the expected outcome.

The other issue is a white screen of death. No error messages, just a white screen with no more access to the front or backend. To make sure this doesn’t happen you should enable debugging, which will give you error messages.

This can be done by editing the wp-config.php file in the root directory of your WordPress installation. Find the line which contains: define( 'WP_DEBUG', false ); and change false to true. That’s all there is to it.

Child Themes

Child themes are separate themes, which are based on a parent theme. They inherit everything from the parent theme, unless otherwise specified. This is the only safe way to modify a theme. As I mentioned earlier, the easiest way to learn is to modify an existing theme. I would like to append that with “and using a child theme.”

If you create a child theme based on Twenty Fourteen, you can still customize it to your liking but you can also update the theme without losing all your changes. This is something you should also keep in mind when working with clients. Always – always – use a child theme.

Creating a child theme is a cinch. Create a new folder in the themes directory and name it anything you like. For our example, let’s name it “child-theme”. Inside this folder create a style.css and a functions.php file. Open the stylesheet and use the following to create the child theme:

You can actually use anything you like in the example above, the only restriction is the line beginning with “Template.” This must contain the name of the directory of the parent theme.

When using child themes the rule is the following: Any time a file is loaded WordPress looks for it in the child theme first. If it doesn’t exist, the same file from the parent theme is loaded. The only exception to this is functions.php. The function files of both themes are loaded, first the child theme’s, then the parent theme’s.

At this point you can switch to your child theme but when you view your site it will be devoid of any styles. Based on our rule above it is easy to see why. The stylesheet is loaded from the child theme, since style.css exists in the child theme, but this doesn’t contain any style information.

The next step is to load the styles of the parent theme. This can be done by enqueueing the stylesheet from the parent. Don’t worry too much about this. Feel free to copy-paste the code below into your child theme’s functions.php. Just be aware that this loads the styles of the parent.

At this point your child theme is exactly the same as your parent theme. You can now start modifying things! You can use the stylesheet to override styles or add your additional rules. If you want to modify the index file, for example, all you need to do is create it.

If you create an empty index file then any page that would use that file will be blank. All other pages will continue to work just fine since they would use the parent theme. You can either start writing your own code into the index file or you can copy-paste the code from the parent and modify that.

The result of this should be the following: You can modify an existing theme to your heart’s content but still be able to update the parent theme or switch back to the parent theme at any time.

The Query And The Loop

The query is the system that “knows” which posts to show on a page and the loop is the part that actually goes through each post and displays them. For example, on your homepage the query looks for the 10 most recent posts. On a category archive page the query looks for the 10 most recent posts from the given category. The query is even used on single pages where it looks up a single post in the database.

The query is something you can modify and use for your own needs, but for now we’ll concentrate on the default usage, which is behind the scenes. We’ll just use the result via the loop.

The loop takes all the posts the query has returned and steps through each of them one-by-one. On some pages – like single pages – there is only one post. This still counts as a “collection” of posts – in this case the collection consists of a single post.

Let’s look at the basic code for a loop and go through it line by line:

The first line uses an if statement coupled with the have_posts() function to figure out if there are any posts returned by the query. If there aren’t any posts, we execute the code after the else section, which notifies the user that there are no posts.

If there are posts we use a PHP loop. There are a few types of loops in PHP. To brush up on the syntax and some more examples take a look at a PHP Loop Types tutorial.

In our code above we use a while loop, which contains the have_posts() function again. This function returns false when there are either no posts in the loop, or no more posts in the loop since we have displayed them all.

Everything inside our while loop gets executed while the value of this function is true. This is exactly what we need. As soon as we’ve displayed the last post the value of have_posts() will be false so the loop ends.

Inside the loop I’ve created a very rudimentary display of a post using the template tags we’ve learned about previously.

The loop should be used in any theme template file which lists posts. Search pages, single post pages, archive pages, the index file – any time you’re listing posts, use a loop!

Custom Queries

It is less common to learn about custom queries so early on, but in my experience it is one of the most sought after features in WordPress. In the section above we learned how you can list posts using the loop, but you are restricted by what is returned by default. What if you want to display upcoming related posts in the same category under a single post? This is easy with a custom query and loop.

You can create a custom query using the WP_Query class. Classes are way above our heads now but using them is fairly straightforward. Here’s an example which shows scheduled posts from a specific category. You can use this to show a “Coming soon in this category” section.

As you can see, this is pretty straightforward. To modify this to your needs you can tweak the contents of the $args array. There are tons of parameters you can use to restrict posts based on their publication date, based on their authors, categories, custom fields and more! Take a look at the WP_Query documentation for a full list.

Now that we have a custom query we can use a custom loop to display the content. All we need to do is prefix the have_posts() and the_post() functions with the name of the variable that holds the query and an “arrow”:

Apart from using referring to our custom query using the format I mentioned above, note that I left out the else part of the loop and I used a HTML list instead of divs. Since this loop is intended to list posts under a complete single post, I thought it would be best to not show anything if there aren’t any posts. In addition, a simple list with links should be enough here for users to click through.

Hooks

WordPress uses an ingenious system to allow you to modify core functions. If you don’t already know this let me stress it as hard as I can: under no circumstances should you modify core files. This means that you can’t edit any file which comes with WordPress by default.

I know that sometimes it seems like it is the only way but it is never the case. Everything you could possibly need can be done with hooks or other methods. Modifying core files is not only dangerous but anything you do will be overwritten by an updated version of WordPress.

Hooks allow you to modify how WordPress works. They come in two flavors: actions and filters. Actions allow you to run a function of your own in specific places in the WordPress code. For example, by using a hook you can execute one of your own functions when WordPress publishes a post. This allows you to notify the author, for example.

Filters allow you to modify data before it is used. For example, you could use a filter to modify the text shown to the user when a post is saved. Instead of “Post draft updated,” you could modify this to say “Your draft has been saved.”

A great example of an action hook is wp_footer. This action is performed just before the closing body tag of a theme. It allows you to add your own stuff to the bottom of a theme without needing to modify the theme’s footer file itself. In your theme’s functions.php you could use the following to add a tracking code to your site:

The first line tells WordPress that we would like to add our my_tracking_code() function to the wp_footer hook. When WordPress loads a page and sees the wp_footer hook it looks up all the functions tied to it and executes them. Our function then adds the Google Analytics tracking code to the footer.

This provides the basis of how plugins work. If you would create a plugin and paste the same code in there you wouldn’t need to modify your theme at all. What this means is that even if you change your theme your Google Analytics code will continue to work seamlessly.

To show you how filters work, let’s modify the content of a post with one. The the_content() filter is run before the content of a post is shown. If we use a hook to tie a function to it we can modify it.

The code below adds the text “Checked by” automatically after each and every single post (or more accurately, any time the full post content is shown).

Note that this time the function received a parameter. Each filter and action can have one or more parameters. You’ll need to check the documentation to see what the specific hook you’re using can do. For a list of actions and filters I recommend the Actions Reference and the Filter Reference or Adam Brown’s WordPress Hooks Reference.

Further Reading

There is a whole lot you can learn about WordPress and a massive body of knowledge available for free. I’ve gathered a few resources for you and categorized them. I hope you find these useful. If you stumble across a particularly great website please do share in the comments below.

WordPress Documentation

Full Courses

  • Codecademy – Codecademy have interactive classes for a number of languages
  • Treehouse – Amazing videos on a variety of coding related topics
  • Tuts+ – Great courses on a number of different topics

Learning About PHP

  • PHP Manual – Official PHP documentation
  • Codecademy – Interactive full PHP Tutorial
  • W3Schools – Great complete PHP tutorial
  • Tizag – Another comprehensive PHP guide
  • PHP Books – Great PHP books, I especially recommend O’Reilly and Apress books

HTML, CSS and Javascript

  • W3Schools – W3Schools has full tutorials to all these languages plus a lot more
  • Amazon Books – Amazon has loads of books on each language or all three at once
  • HTML 5 Doctor – A great place to learn about new tags and the subtleties of HTML5

Getting Help

Advanced Topics

  • Sass – CSS with superpowers
  • LESS – CSS with support for variables and functions
  • OOP PHP – Object Oriented PHP
  • SQL Tutorial – Learn how to query the database yourself
  • Laracasts – Modern PHP and Laravel Tutorials
  • Koala – Free, cross platform code compiler
  • Prepros – Premium, cross platform code compiler
  • CodeKit – My favorite OSX code compiler
  • Grunt – Free, terminal based code compiler

Websites To Follow

What resources do you use to learn WordPress programming? Share your tips in the comments below.

Image credit: James Cridland.

]]>
http://premium.wpmudev.org/blog/getting-started-with-wordpress-development/feed/ 11
How to Create a WordPress Child Theme http://premium.wpmudev.org/blog/how-to-create-wordpress-child-theme/ http://premium.wpmudev.org/blog/how-to-create-wordpress-child-theme/#comments Sat, 29 Nov 2014 13:00:54 +0000 http://premium.wpmudev.org/blog/?p=134456 WordPress themes can be amazing but there are so many examples of little things we all want to change. A color here, a font size there, perhaps use a different call to action on the buttons?

The problem is that modifying a theme even slightly prevents you from updating it to a newer version in the future, because if you do try to update, you lose all your changes.

Child themes solve this by allowing you to use all of the functionality of your chosen theme while allowing you to update it without the fear of losing your modifications.

In today’s Weekend WordPress Project, I’ll explain why you should be using a child theme and how you can get the job done.

Child theme
Easily create a child theme for your WordPress website.

How Child Themes Work And Why Use Them

Child themes are separate themes that rely on a parent theme for most of their functionality. If you are using a child theme, WordPress will check your child theme first to see if a specific functionality exists. If it doesn’t, it will use the parent theme. This is great because it allows you to modify only what you need.

Child themes should always be used if you plan on modifying even a single character in your theme. There are two very good reasons: updates and organization.

Updates

If you modify a theme without using a child theme you have two choices: You can opt to not update your theme in future, or you can update and lose any changes you’ve made to your theme.

The later option would technically work, but it is not recommended. Even if your changes are easy to copy and paste, why spend two minutes on an error-prone task on each update?

Not updating your theme should be out of the question. Almost all “why your website was hacked” lists contain outdated software as a top cause for security issues. You should always keep WordPress, your themes and plugins up to date, no exceptions.

Organization

When you add code to an existing theme you are adding to a codebase, which may be thousands and thousands of lines. Developers working on your site (and, indeed, you yourself) will have a hard time tracking down your changes. At least one direct result of this will be an increased development bill.

Since child themes fall back on parent themes unless otherwise specified, your child theme is essentially a changeset to an existing theme. This can result in extensive changes even though the child theme only has a couple of files and maybe 100 lines of code.

Creating A Child Theme

Creating a child theme is extremely simple, so much so you can copy and paste my example below.

To create a child theme for your theme, you will need to do the following steps:

  1. Create a theme directory in your WordPress install
  2. Create a stylesheet with information about your child theme
  3. Pull in the styles of your parent theme

Once these steps are completed you can activate your child theme and your website will look exactly the same as before, but it will be using your child theme.

So let’s go through the above steps in detail. For this example, I will be creating a child theme for the Twenty Fourteen default theme.

1. First, go to your theme directory and create a folder for your new theme. You may name it anything you’d like. For clarity’s sake, I will name my theme twentyfourteen-child.

2. The next step is to create a stylesheet file. This must be named style.css. Copy and paste the following code into the file you’ve just created:

The two necessary items in the code above are the lines starting with “Theme Name" and “Template.” The theme name tells WordPress what the name of your theme is, and this is displayed in the theme selector. The template tells WordPress which theme it should consider as the parent theme. Most of the others are self-explanatory, with the exception of the text domain and the tags. The text domain is used for translating strings. The text domain should be unique for your theme and should be used whenever you use translation functions. See I18n for WordPress Developers for more information. The tags section is a list of tags that are used by the WordPress Theme Repository. For this example I looked at the style.css file of the parent theme and simply copy-pasted the tags from there.

3. At this point your child theme works just fine. If you activate it and reload the page all your content will be there but, it will have no styling information. I mentioned before that WordPress first looks for functionality in the child theme and if it isn’t present it falls back on the parent theme.

In our case we do have a stylesheet, so WordPress figures it shouldn’t load the parent file’s. To make sure we load the parent file’s stylesheet we will need to enqueue it. This can be done in the theme’s functions.php file, so go ahead and create that file now. In this file, copy-paste the following code:

If you have no idea about PHP and you just want to change some styles, don’t worry about why this works. Feel free to go into your stylesheet file now and start making your changes. If you would like to learn more about enqueueing we have you covered right here on WPMU DEV with Adding Scripts and Styles to WordPress the Right Way With Enqueueing.

Child Theme Mechanics

So how does a child theme actually work? Child themes work on a file-level. When a file is used during the process of loading a theme it checks if it is present in the child theme. If it is, the content of that file is used. If it isn’t, the same file in the parent theme is used.

There is one exception to this rule, the theme’s functions file. The functions.php file in both the parent and the child theme is loaded. If the child theme’s functions replaced the parents you would either have a malfunctioning site, or you would need to copy-paste the entire contents of the parent theme’s function file into the child theme’s which would sort of defeat the purpose of extending a theme.

The workflow when modifying functionality is the following. If you want to make changes to the header, copy-paste the parent theme’s header.php file into your child theme. Edit the file to your heart’s content, save it and enjoy the fruits of your labour.

Some Notes For Theme Makers

If you make your own themes there are a couple of guidelines you may want to follow to make child theme creation easier. The two most important ones are learning the difference between get_stylehseet_directory() and get_template_directory() and creating pluggable functions.

The Right Directory

When linking to assets using the mentioned functions you should always be aware that the get_template_ family of functions will always point to the directory of the parent theme while the get_stylesheet_ family of functions will always point to the child theme’s directory.

In the example above the first link takes its image from the parent theme, the second takes it from the child theme. There’s no good answer to which one you should use, it’s up to you.

The upside to using get_stylesheet_directory_uri() is that child theme developers can use their own image by simply creating it in the proper location. On the other hand, if the image doesn’t exist in the child theme it won’t be shown at all.

The reason for this is that if a child theme is active the get_stylesheet_directory_uri() function doesn’t check (and doesn’t know) which file you are loading so it won’t check for its existence, it will always spit back the URI for the child theme.

Modifiable Functions

The other method you should use is what WordPress calls pluggable functions. This makes it possible for child theme authors to overwrite the functions you define in the parent theme. This involves wrapping your functions in function_exists() checks.

Let’s presume you create a function for a customized post meta display named my_meta(). There is no way a child theme can modify this function because it can not be defined twice. The solution is to only create this function if it hasn’t been defined (remember, the child theme’s function file is loaded first).

Conclusion

Using a few very simple copy-pastable steps you can create a future-proofed environment for your theme, which will save you a lot of headaches. While it may be tempting to use the built-in theme editor in WordPress, it almost always causes more issues than it solves if you’re not using a child theme.

Take a few minutes to follow along the tutorial here and your website and your developer will thank you for it. Finally, If you have any great tips about child themes, do let us know.

]]>
http://premium.wpmudev.org/blog/how-to-create-wordpress-child-theme/feed/ 19
Creating Cool Custom Controls for the WordPress Theme Customizer http://premium.wpmudev.org/blog/creating-custom-controls-wordpress-theme-customizer/ http://premium.wpmudev.org/blog/creating-custom-controls-wordpress-theme-customizer/#comments Fri, 28 Nov 2014 13:00:35 +0000 http://premium.wpmudev.org/blog/?p=134140 In a recent article about creating theme options with the WordPress theme customizer, we looked at how you can use the Theme Customization API to create awesome WordPress-standard options to support your theme.

Today we’re going to take things to the next level and look at how we can add our own custom controls to the customizer.

By default, the only controls the API offers are text field, checkbox, radio, select and dropdown pages. By creating our own control class we can step beyond these boundaries and create even more controls, including a implement number box, a page template selector, a Google Font selector, a yes/no button and even a range selector.

In this article, we’re going to create a simple text area and a more complex latest post selector.

Theme customizer controls
Create custom controls for the theme customizer.

Using Included Controls

The WP_Customize_Control class is responsible for generating all the controls you see in the theme customizer. When you use the basic set (text field, checkbox, etc.) you don’t have to use this class, it is abstracted away.

As a reminder, let’s take a look at how to create a simple control. For more information about where to put this code, check out our customization API tutorial mentioned above.

There is no trace of WP_Customize_Control here. WordPress creates the object for you, and as the Codex puts it:

Alternatively, it is not required to instantiate a WP_Customize_Control object. WordPress will check to see if you are passing in an object and, if absent, will create a new WP_Customize_Control object with the arguments you have passed in.

Based on this, the following code is equivalent to the snippet above, but it uses WP_Customize_Control directly.

Custom Controls

To create our own controls we can extend the WP_Customize_Control class, adding some of our own functions. Let’s make one together, a simple text box which is – surprisingly – not available by default. Thanks to the theme customizer snippets for this example.

One question I get asked a lot is how do we know which functions need to be defined? The simple answer to that is to look at a few examples others have written. The more complex one involves looking at the source code for the base class. If you have a look in the WordPress Github Repo you can see the code for this class.

For example, in the base class the public variable $type is defined as text. Looking at the code of the class there is no setter method which has the task of setting the value of this property. This is why, when extending the class, we define it ourselves. The render_content() method defines controls, which is why the example above has added this function.

It’s important to note that $this->link() is required for the Javascript in the theme customizer to work. $this->value() can be used to retrieve the value of the setting we are manipulating.

There are others methods we can – and will – use to enqueue styles and do other tidbits, but for our simple example will suffice.

Once we have defined our textarea control type we can now use it in a control like so:

Latest Posts Dropdown

So let’s take what you’ve learned so far and create another relatively simple control. This time we’re going to create a dropdown that lists our latest 10 posts:

Here’s what our dropdown looks like on the frontend:

latestposts
A simple dropdown box listing 10 latest posts.

The process is much the same, the only addition here is a custom loop used to display the posts. One way we could improve our work considerably is to easily modify the posts in the query. We could use this same control to show pages, or draft posts or even custom post types. Let’s modify how we add our control and then update our class to work:

To use this new post type control we must define it as a public variable in our class. The way the base class (WP_Customize_Control) works is that it looks at the defined variables and parses all data from the given arguments into them.

As a result we only need to modify two lines in our class. Keep an eye out for the definition of the post type variable at the top and the usage of $this->post_type in our query:

Conclusion

Creating custom controls takes a bit of extra time, but don’t forget that the better your controls, the more time you save for your users. Saving a minute of time for a single user could translate to hundreds of hours if your theme has a couple of thousand downloads.

Ultimately, the goal should be to create controls that fit a specific setting. If you need to select a range, why create two text fields when a jQuery range slider could do the job much better?

If you’d like to get your hands on some great custom controls, Paul Underwood has kindly released 12 custom controls. Use these to your heart’s content!

Have you created custom controls? Share your ideas 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/creating-custom-controls-wordpress-theme-customizer/feed/ 0