WordPress Tutorials http://premium.wpmudev.org/blog The WPMU DEV WordPress blog provides tutorials, tips, resources and reviews to help out any WP user Sat, 28 Feb 2015 13:00:06 +0000 en-US hourly 1 http://wordpress.org/?v=4.0.1 WordPress Tutorials http://premium.wpmudev.org/blog/wordpress-theme-files/ http://premium.wpmudev.org/blog/wordpress-theme-files/#comments Sat, 28 Feb 2015 13:00:06 +0000 http://premium.wpmudev.org/blog/?p=137899 Are you keen to start modifying your website but feel completely lost at step one?

WordPress tutorials are often simple, but start with phrases like “open your theme’s functions.php file,” which can instantly throw a beginner off track. Where is this file? Open it in what? Where is my theme?

There’s absolutely no shame in not knowing any of these things. It would be a funny, old world if we were all the same and knew the same amount about the same things!

In this article I’ll try to introduce you to the very basic WordPress concepts when it comes to code, ones that are often skimmed over, even in beginner articles.

There is only one pre-requisite if you want to follow this article – owning a website. The gist of what is said will be easier to understand, but to follow along you’ll also need to have a domain name and a hosting account. If you don’t have one yet, consider signing up for one.

How Websites are Modified

On a very basic level websites are nothing more than files stored on a computer somewhere. Your browser receives the content generated with these files and displays it to you. To modify a website all you need to do is access the correct file and edit it. This requires the knowledge of three things:

  • Where the files are
  • How to edit them
  • Which file to edit

When you are in possession of this information you generally do the following: You connect to the server where your website is stored, you navigate to the file you need and download it to your computer, you open it on your computer and modify the content, and you upload the file to its original location, overwriting the old version.

Connecting to a Server

In order to upload and download files to a web host’s server, we use FTP – or File Transfer Protocol. There are a number of FTP tools you can use. A great, free one is called Filezilla. If you don’t already have this software, go ahead and download it now.

When you open the application you should see a bar at the top where you can enter a host, a username, a password and a port number.

Filezilla quick connect
The FileZilla quick connect bar

To fill out these forms you’ll need to look up your FTP access details. Most hosts allow you to log in to a control panel, which has a dedicated section displaying your login credentials. Some hosts allow you to create your own username/password combinations for FTP accounts. If you are unsure you can always get in touch with your host’s support team.

Media Temple Access
My access details at MediaTemple (with NSA style redaction of sensitive info!).

Finding Our Files

Once you enter your details and click “Connect” you will see a list of files and folders. A server (the computer containing your website) may have a lot more files than just the ones for running your site. We know that the files we are looking for are somewhere here in theory, but which ones!

This may be a difficult question. You may need to refer to your control panel or your host’s customer support. In the image above you can see the “FTP path to HTML directory” section. This means that I’ll need to go into the domains folder, then the danielpataki.com folder, then finally the html folder. If in doubt, ask your host where the files for your website are and they’ll be able to help you out.

Once you know the credentials to access your files and where they are you can make your life easier by creating a connection preset. Instead of having to type all your info you can save it and navigate to the required directory automatically each time you connect to your site via FTP.

Managing Sites

Use the top-left icon to open the site manager in FileZilla. This window allows you to save your pre-configured settings. Once you create a new site you can fill out the details.

FTP Details

Make sure to switch to the advanced tab to fill out the default remote directory. This determines the directory the FTP app switches to right after connecting.

Editing a File

Let’s say you’re following a tutorial which calls for the editing of a specific file. Once you’ve found this on the server you can double click it or drag it from the right-hand pane to the left hand one. This will download the file to your computer. You can now open this file with any text editor (more on this later).

When you’re happy with your changes you should save the file, then go back to FileZilla and drag the modified file from the left-hand pane to the right. The application will ask if you want to overwrite the file. If you choose to do so the file will be transferred to the server, overwriting the original version.

Using Text Editors

A text editor is an application that can open, edit and save text documents. Ideally the editor shouldn’t add any extra information to our document. When you create a Word document a huge amount of information is contained within the file that has nothing to do with the content. File sizes, colors, positioning, and so on.

A text editor is similar to Notepad on Windows or TextEdit on Mac. Most programmers use more versatile tools but if you only have the basic ones installed, they will do just fine.

A few great text editors include Notepad++, Sublime, Coda and Atom.io.

Editors with Built-in FTP

Some editors have built-in support for FTP. Note that the flow I described previously makes you switch between your text editor and FTP application constantly. Editors like Notepad++ that have built-in FTP provide a self-contained system – no more switching between apps.

Coda FTP
FTP Files in Coda – a popular Mac text editor.

Working With FTP

Hopefully you now understand the mechanics of working with files. I want to make it clear that this is something that needs to be practiced. FTP is second nature to a developer but I remember how alien it was when I started out. Just because you see other people handle these concepts naturally doesn’t mean they are easy – it just means that developers have a lot of practice.

The truth is that when I started I opened the wrong files many, many times. I didn’t understand what I was transferring where or why my changes didn’t show up. Mistakes likes these are all perfectly normal and with practice you’ll get the hang of it!

Common WordPress Files and Locations

We’ve taken a look at file locations twice and you should now know how to locate your website’s root directory – the folder that contains all your website’s files. However, many tutorials won’t give you the exact details of all the files. They’ll say things like “open your theme’s stylesheet.” If you don’t know where the theme is stored and what a stylesheet is, you’re in trouble!

Below is a list of some of the common terms used and how to find them. These all assume that you are using a WordPress site of course! Keep in mind while reading the list that all of my descriptions are relative to your website’s root directory (unless otherwise stated).

Themes Directory

The themes directory is located within wp-content and is named themes. This is the directory that contains all the themes available on your website. Each individual folder in here is a separate theme.

Current Theme Directory

This can also be referred to as the theme directory (singular) and is a folder located in the previously discussed themes directory. The directories are all named so you should be able to find the one you need easily. The current theme you are using is displayed in the “Appearance” section in the WordPress backend.

Plugins Directory

This one is found within wp-content and is called plugins. This folder contains all the plugins available to your website. Some plugins (rarely) may only be composed of a single file in which case they will be stored directly in this directory. Most plugins are stored within their own directory.

Theme Stylesheet

This refers to the stylesheet of your current theme. This file governs how your website looks: how big boxes are, what color the text is, which side your sidebar is on, and so on. It is the style.css file within your current theme directory.

Theme Functions File

This file governs various features within your theme, like how comments are displayed, the image sizes supported by your theme, and maybe even custom post types and taxonomies. This file is the functions.php file in the current theme directory.

Theme Index File

This file is used to display the front page of your website if it shows your latest blog posts. It is the index.php file within your current theme directory.

Theme Template Files

There are a number template files within the current theme directory. The index file is a template file which displays the front page. The single.php file is responsible for single posts for example, page.php is responsible for static single pages. A pretty good list of all template files can be found on the Template Hierarchy Codex page

Main Plugin File

The main plugin file is the initial file loaded when your plugin is active. It usually bears the same name as the folder it is in. The plugin folder can be found in the plugins directory. If the folder’s name is my-plugin, the main plugin file is within this folder and is probably named my-plugin.php.

Following Includes

PHP is a server-side language and allows you to include the contents of one file into another. This can be done using the PHP functions include(), require(), include_once() and require_once() or with the WordPress function get_template_part().

If you see any of the first four you can follow the path given within these functions to find the file. If get_template_part() is used it may look something like this:

get_template_part( 'post', 'simple' )

What this means is that the file being included is post-simple.php. So why is this important?

To improve readability, coders tend to separate functionality into different files. A full page on your site contains code for the header, the footer, the sidebar, the posts shown, and so on. These may be included, instead of all the code being put in one place, just to make things easier to modify.

Overview

Hopefully you now have a rudimentary understanding of working with WordPress files. There are more complex and more useful ways of coding, but this is not something you need to be concerned with at the moment. The best course of action is to get proficient with FTP and then moving on when you’ve had plenty of practice.

Are there any other beginner gripes you have? Some fundamental steps that tutorials always skip over that you would love to know how to do? Let us know in the comments below and we’ll try to tackle some of the most common ones.

]]>
http://premium.wpmudev.org/blog/wordpress-theme-files/feed/ 3
WordPress Tutorials http://premium.wpmudev.org/blog/how-wordpress-becomes-unusable/ http://premium.wpmudev.org/blog/how-wordpress-becomes-unusable/#comments Thu, 26 Feb 2015 12:00:50 +0000 http://premium.wpmudev.org/blog/?p=137717 I’m sure many of us have been there: Loading times on your site are terrible, perhaps you’re getting a few timeout errors, the admin is sluggish, and the overall experience of using your WordPress site is declining. Rapidly.

Unfortunately, small annoyances can quickly build up and  turn into financial issues. A slow website can directly affect conversions and sales on the front-end and lead to frustration and stress on the management side of things.

In this article I want to take a look at why these slow-downs happen and what you can do to prevent them. As a result, you should be able to better manage your website to ensure that it runs as efficiently as possible for as long as possible.

Why Websites Become Slow and Unusable

Throughout this article I will be talking about “slow websites” quite a bit. I want to make it clear that I am talking about slowness as a result of some kind of fault, which can be fixed, rather than conscientious efforts of speeding up websites by optimizing them.

An example will make this clear: Deleting a plugin, which loads 50 Javascript files in your website’s header would fall under the purvey of this article. Moving your images to a CDN for faster loading times would not.

So what can cause a website to become unusable? In my experience there are three basic issues we need to investigate. I’ll go through the causes first and then provide some actionable solutions in the next section:

  • Plugin overload
  • Sloppy code
  • Flawed processes

1. Plugin Overload

Having too many plugins can be the curse of an otherwise perfect website. Each plugin you use may add its own scripts and styles, considerably increasing the requests made per page load. The number of requests made is extremely important because two requests to download 100kb files will take a lot less time that 20 requests to download 5kb files.

You may also end up with duplicate functionality. If you use Easy Foundation Shortcodes you get a lot of shortcodes for using Foundation elements. However, you may already have shortcodes installed for grids and alerts. These don’t chew up too much processor time and memory, but each plugin is still loaded and initialized whether it is used or not.

…You’re now looking at 800,000 requests a day. That’s 9.3 requests a second, or two requests in the time it takes for you to blink.

The idea here is that little things can add up very quickly if your website has a generous number of visitors. If you have the absolute minimum number of plugins your website may make 20 requests per page load. If you have 100 visitors a day that would be 2,000 requests fulfilled.

If one of your articles is shared on social media you may have a day with 20,000 visitors. Suddenly you get 400,000 requests to you server, which still may be fine but imagine if you have tons of plugins, which all need to be loaded, and each makes another 20 requests. You’re now looking at 800,000 requests a day. That’s 9.3 requests a second, or two requests in the time it takes for you to blink.

2. Sloppy Code

If we would figure out the percentage of speed decreases caused by each of the issues we listed, sloppy code would win comfortably. While plugin overload is a problem, the majority of speed decreases experienced by installing lots of plugins can be boiled down to sloppy code.

Let’s put the number of requests made into perspective: If you optimize the heck out of your website you could push the loading time down to 600ms on a capable server. If you have lots of requests this may be increased by as much as 200ms, which is a whopping 33% of the base loading time. However, the base loading time is so small that the number of requests is not such a huge problem.

If you have a base loading time of 8 seconds and you apply the same logic, you are looking at an extra 2.64 seconds of loading time, which is huge. In real life the ratio isn’t so drastic but the gist of it holds up well.

The fact that your plugins load assets is not the problem, the problem is when they do this unnecessarily or wastefully. Plugins should concatenate scripts and styles where possible to reduce the number of requests.

Plugins also have a tendency to put unnecessary pressure on the database. This is especially true for products that retrieve posts based on complex criteria or add some sort of statistics to your site. All these tasks can be done efficiently but plugin authors have a tendency to do things quickly rather than thoroughly.

All the problems above increase exponentially when talking about themes. Since themes provide the forward-facing functionality of your website you may have the need to modify things in there regularly. Regular changes to code will inevitably cause the downfall of any website unless managed closely, we’ll take a look at this soon.

Multiple developers with multiple methods of working will write wildly different looking code, muddying up the theme, making it impossible for a developer to make sense of it as a whole.

The reason it causes problems is that code will become unreadable. Multiple functions may exist for the same functionality, old functions may not be removed by new developers since they may not know what they are for. Multiple developers with multiple methods of working will write wildly different looking code, muddying up the theme, making it impossible for a developer to make sense of it as a whole.

This results in patchwork of code instead of proper development. When replacing the share section in your posts, the proper way to do it would be to identify all the functions which contribute to it, remove them all and implement the new functionality. If the code is a mess it’s easier to either comment out the hook that displays it all or to remove the functions in the template. This will leave all other functions that contribute to counting the number of shares, figuring out the Twitter text, etc intact and in the code base, even though they aren’t used at all now.

3. Flawed Or Missing Processes

Let me describe a situation which may sound familiar: You have a new website based on a commercial, free or custom-made theme. Everything works perfectly but you would like custom-made share buttons.

A developer comes in and implements this for you by modifying the functions file, adding some images and modifying the single post template. It works perfectly but you would now like users to be able to log in via Facebook. Pretty easy, there’s a plugin for that!

A few months later you decide to change the logo and you want to feature a key element of it in the share buttons. In comes another developer. He removes the code from the single post template and adds his own, using fancy SVG to draw the share icons.

Even over the course of these three changes, several problems could be introduced: The share button and the login may require loading external JS from Facebook, and perhaps adding Facebook tags to the page. If done hastily all three features may add it independently, potentially loading the script three times. At best this will slow down the website, at its worst it may break your Javascript altogether. When implementing the third feature the developers may take all sorts of shortcuts. If they can’t find how it works they may just remove the relevant code from the single post template and add their own functions. This will work fine but may leave unused functions in the functions.php file. Over time this leads to mangled code that no developer would want to work with.

Flawed processes are not just relegated to the development side of your website. Admins and editors can be just as sloppy. They don’t lay out clear guidelines for formatting resulting in random headers, sometimes image alt text and titles are defined, sometimes they aren’t. Images are sometimes beautifully formatted, other times not so much. These little inconsistencies add up and in contrast to coding issues, they are much more difficult (or laborious at least) to fix.

Keeping Your Website Usable

In my opinion, preventing your site from becoming unusable comes down to strictly enforcing processes. This won’t really help you if you already have a sluggish website, so let’s look at some immediate remedies first:

Removing Unnecessary Plugins

Are you sure you’re using each and every one of your 50 plugins? Did you install BuddyPress to test it out rather than actually use it? Perhaps you have a number of admin tools such as importers, image regenerators and so on activated. Weed out these “obvious” ones first. If something isn’t being used and you’re not planning to use it in the near future, get rid of it. For admin plugins, which are needed but rarely used, consider deactivating them until they are needed.

Plugins
Do you use all of the plugins installed on your site?

What about plugins you aren’t sure of? Do you need Contact Form 7, Advanced Custom Fields, Layer Slider, etc? A good place to start is installing two plugins (I hope you appreciate the irony here): Unused Shortcodes and Shortcode Lister. Shortcode Lister will list all registered shortcodes, while Unused Shortcodes allows you to enter a shortcode to see if it is used. Track down the plugins responsible for the unused shortcodes and get rid of them.

Keep an eye out for plugins that perform the same function. I see a lot of cases where an admin installed Contact Form 7 for a contact page and then six months later needed a form for something else and, forgetting Contact Form 7 was already installed, searched and installed Ninja Forms or Visual Form Builder. These plugins use shortcodes so you can figure out where they are used with the plugins mentioned above and modify your forms to use the same plugin – delete the rest.

A third category of unnecessary plugins is spawned by unnecessary website features. Do you really need avatars to turn into hover cards. Do any of your visitors use this? Are you sure you need the homepage slider or is it just eye candy? Try and scan your site with a critical eye to find plugins you’re using that detract from the site’s usability instead of adding to it.

Optimizing the Database

If your database tables have lots of entries they may become defragmented, i.e. they operate with a lot of overhead. This can be the case for data-intensive postmeta and usermeta tables. I worked on a site recently that was suspended for using too many resources on its server. A rebuild of the whole site is coming soon but a simple optimization of the database tables allowed us to speed things up in the short term to get us through the rebuild.

To optimize your tables you will need access to your MySQL database. This can usually be accessed from your domain/host control panel. Getting access may require a username and password. Some hosts provide this information in the control panel somewhere. In other cases your developer may have created the database for you and written down the access in an email. If all else fails, try opening the wp-config.php file in your root directory. This file has database access credentials, which look something like this:

define( 'DB_USER',     'username_here' );
define( 'DB_PASSWORD', 'password_here' );

Once you gain access to the PHPMyAdmin interface you should see a list of databases on the left. Choose the one related to your website. You can find the database name in the wp-config.php file if needed. If you click on the database you should see a list of tables within on the right.

MySQL Database
The bottom of the database – click for a larger view

In the larger view the right-most column shows the overhead, while the second-last column shows the amount of content stored. Before we optimized the database for the rebuild project I’m working on, the overhead was something like 50Mb – ripe for optimization. If you have an overhead, which is a significant percentage of your stored content, I recommend you optimize your database. Select the tables to optimize using the checkboxes on the left, then select “Optimize Table” from the dropdown on the bottom.

Be aware that this may only be a temporary measure. All databases acquire overhead as time goes by but how much and how fast is a factor of code quality. The more wasteful your queries, the more temporary tables needed the quicker overhead is amassed.

Getting a Server Upgrade

If you are desperate to speed things up a server upgrade may help you out. Code issues often cause memory problems, which can be dealt with by throwing more memory at the problem. You can contact your host to ask for this but it will cost you. Most VPS hosting plans have upgrade options, so check out the prices with your current host or consider finding a new host.

While this may provide some breathing space it is the absolute worst way to solve the problem of an unusable website. It is the equivalent of using duct table to hold your car’s bumper in place. Sure, it may hold out until you get to the mechanic, and then again, it may not. In some cases a temporary option is better than nothing, just be aware that this is a crisis-aversion technique, not a solution.

Use a Caching Plugin

Again, not a solution, but a useful addition to your website nevertheless. Caching can take a load off your server by essentially storing the state of a page and serving it as static HTML. This reduces processor and memory load, which can buy you some time while working on the core issues.

WP Super Cache or W3 Total Cache are both great options.

Code Overhauls

Code overhauls can provide benefits almost instantly but are more difficult to orchestrate, especially with a muddied codebase. There are some techniques that can help. I recommend looking for slow queries first. You can do this in a couple of ways, the quickest would be to install Debug Queries, which lists all queries from the front-end and allows you to identify wasteful ones.

MySQL has a built-in slow query log but you may need to ask your host where this is, or you may even need to get it turned on.

Wasteful queries are the cause of most sluggish websites. Not only do they have an immediate speed impact, the problems are amplified over time, especially with increasing traffic. Once you’ve found where they are you can rewrite them in your code, disable the functionality or get rid of the offending plugin.

Some authors have the tendency to use the database a lot more than needed. Some plugins and themes may use multiple rows to store settings as discrete data. In most cases this isn’t needed – you can aggregate them into arrays and store them in one row.

Code overhauls are very difficult to pull off on a completely wasted site. Even though code can be taken apart into functionally independent sections the whole tends to be more than the sum of its parts. With a severely jumbled website a complete re-coding can take less time and effort and produce 200% better results.

Management Policies and Processes

I think by far the most effective solution to preventing your website from ageing is putting management policies in place which cover all aspects of the business. Standardizing everything you do leads to countless benefits, surpassing even your original goals:

  • Your business will be more transparent
  • Tasks can easily be taken over by others
  • Everyone’s understanding about the site will increase
  • Implementing new features becomes much easier
  • Backtracking is built into the system
  • Mass changes become easier
  • Security will increase
  • Website speed will stay fast

I recommend creating at least two documents, which will govern two main areas related your site:

  1. Development guidelines should dictate the method development, testing, deployment, the style of code, and so on. It serves to standardize the coding process so any developer can take over after reading the guidelines.
  2. Administration guidelines are all about how you manage the website. This can include the editing guidelines for content creation, image guidelines, SEO actions taken per post, update policies, plugin usage policies and so on.

If you have any other major processes such as advertising, sales, etc. you can create detailed guides for those as well. For any process that requires the same tasks over and over I recommend creating a step-by-step guide, describing what to do. Ideally a newcomer should be able to sit down with the guide and a computer and do what you do.

Learn Some Code

I try and stress wherever I can that learning code will make everyone’s lives so much easier. You don’t have to become a developer but knowing roughly what’s going on behind the scenes will provide you with benefits you never knew were there in the first place.

You’ll be able to choose your plugins better, you can keep a closer eye on your site’s code, communicate with developers more easily, spot potential problem points ahead of time, and much more.

Conclusion

If we take a step back and take a bird’s eye view, there really is only a single factor that contributes to websites slowing down: Human habits (not necessarily errors).

WordPress itself is fairly efficient, but plugin and theme authors introduce smaller and larger issues through negligence, the excitement to publish a product, carelessness and so on. Users then enhance this problem by throwing unnecessary plugins at their site, being inconsistent, and sometimes just being a bit lazy.

If you found that a bit offensive, take comfort in the fact that everyone does it. I preach about perfect websites with perfect guides but I don’t always follow my own advice either. Take into account the type of website you have. If it’s a small personal website then you can get away with a lot less. If you’re making thousands of dollars with your eCommerce site, paying more attention to these things will not only prevent headaches down the road but probably directly increase sales.

Do you have unused plugins activated on your site? Is your site running slow and this post has offered a lightbulb moment? Let us know your thoughts in the comments below.

]]> http://premium.wpmudev.org/blog/how-wordpress-becomes-unusable/feed/ 14 WordPress Tutorials http://premium.wpmudev.org/blog/streamline-client-consultations/ http://premium.wpmudev.org/blog/streamline-client-consultations/#comments Wed, 25 Feb 2015 13:00:00 +0000 http://premium.wpmudev.org/blog/?p=137436 If you’re a freelancer or run a business that provides consultations, it’s important to make yourself readily available to potential clients.

Emailing back and forth to arrange times for meetings is inefficient, time consuming and, frankly, outdated.

Fortunately, streamlining consultations is a straightforward process to set up with WordPress. Using our Appointments + plugin and your favorite video chat plugin, you can easily set up and conduct consultations with clients, all from your own website.

I have successfully set this up for my own business and as a result I have decreased my workload while increasing sales. In this tutorial I”ll show you how you can do the same.

An Appointments + booking calendar with a date selected and available times have appeared.
Enable your clients to automatically schedule consultations (and even pay for them!) right from your WordPress site. It can save both you and your clients a lot of time.

Getting Started

Before we begin, make a backup of your entire site. We’ll be installing plugins so it’s best to have a backup in case of compatibility issues with existing plugins.

If you’re not sure of the best best way to backup your site, there are many options out there like our Snapshot plugin, VaultPress or BackupBuddy.

Once that’s done, install and activate Appointments + along with a video chat plugin that works for you. If you’re not sure what to use, our post Best WordPress Video Chat Plugins – Based on Your Needs may help you make a decision.

You could also opt for a service such as Skype or Google Hangouts instead of a plugin. While they may not be the most professional tools out there, but they can be used as backup options in case your clients prefer these methods.

Create Custom Pages

There are a few key options that you need to pay close attention to in order to achieve the best results. First, create the following new pages:

  • Book Your Consultation – Or name the page whatever suits your site. As the name suggest, this page will be where potential clients can book a time to talk to you.
  • Booking Confirmation – This page will let clients know their consultation was booked successfully and provide any further details.
  • Cancellations – If your clients need to cancel, this will be the page they access to make it happen.

Once that’s all done, visit “Shortcodes” under the “Appointments” tab in your dashboard to view the many options available to you. You’ll need them to display everything from booking capabilities to payment options.

Your specific needs will dictate which shortcodes are best to use. If you’re a business with many staff members, you can choose [app_service_providers] to display a selectable dropdown list of  everyone who is available for your clients to book. If you’re a freelancer or life coach like me, you won’t need this one.

Here’s the successful structure and shortcodes I use for the “Bookings” page to give you an idea of what to add to your page. I also added instructions so my clients could more easily navigate the process:

I’ve included the [app_login] shortcode for clients who have an account. This shortcode will give you the option of offering a discount once clients are logged in. I also added [app_paypal] to accept payments through – you guessed it – PayPal.

My clients will be able to select one of my three types of consultations with [app_services], a calendar with the available time slots will be displayed with [app_monthly_schedule] and a button will appear so my clients can switch to view my calendar in advance, one month at a time with [app_pagination month="1" date="0"].

You can also add information about your consultations by customizing the [app_services] shortcode to include a description of the service or even a staff member. You can also choose which order your consultations are listed and if you’d like to display a thumbnail of a featured image.

Adding a world clock to this page will help potential clients from around the world book a consultation with you since they’ll easily be able to determine what your timezone is compared to their own. I chose to use the clock widget from WorldTimeBuddy.

You can easily change the color scheme to suit your site’s style. Here’s an example of what it looks like in action.

An example of the WorldTimeBuddy clock widget displaying the time in PST and the visitor's time in EST.
In the bottom right-hand corner there is also an option for the visitor to switch between the default 12 hour clock or military time.

Your confirmation page could display important details about where the consultation will be held and other relevant information. You can also choose to have a copy of this emailed to your clients upon a successful booking in the settings.

You can even display your client’s currently booked consultations with the shortcode [app_my_appointments].

You can also allow automatic cancellations, but you will need to add a parameter to this shortcode. It will look something like this: [app_my_appointments allow_cancel="1"].

Whether or not you choose to allow your customers to cancel consultations on their own is up to you and you can toggle the options for it on the settings page.

Finally, your cancellation page could simply have a bit of text confirming the consultation has been deleted and refunded. You could also add a button to book another session in case the cancellation was a mistake.

Now that your pages are set up they’ll look great except for the “Bookings” page since we haven’t yet adjusted any of the settings.

Enter Your Desired Settings

Once you access the “Settings” page through the “Appointments” tab that appears in the dashboard, tips will be displayed to help you set up the Appointments + plugin and choose the best settings based on your needs.

Go ahead and do this, but I’ll run through the specific settings you’ll need to really make bookings as automatic as possible.

Under “Accessibility Settings,” setting “auto confirm” to “yes” will give you the option to allow clients to book free consultations if you provide that option.

This is particularly helpful if you’re a web designer. You will be able to meet with your clients for an information session where they tell you about their requirements.

This is also the section where you can set the option for your clients to cancel their own booked consultations.

The accessibility settings are shown and the option to allow customers to cancel their own appointments is set to "yes" and a cancellation page has been selected.
Allowing your clients to cancel their own appointments is very handy as it helps to eliminate “no shows.”

If you set the option to allow clients to cancel their own appointments to “yes,” you’ll also need to select your cancellation page in the next option as I have already done in the above example.

If you would like clients to login to book a consultation, this option is also listed at the end of this section.

When you get to the “Display Settings,” at the bottom, you’ll notice an option called “Additional fields” with the ability to add new ones.

The "Add new field" setting under the"Additional fields" option.
This option may look unnecessary, but it’s the key to streamlining your consultations.

This is where things get interesting. We’re going to set up custom options so your clients can choose where they would like to meet.

In the “field label,” type in the location in a descriptive way such as “Meet me on Skype.” Select “Checkbox” under “Field type” and leave the checkbox for “Required?” unchecked. Now click the “Add” button. Now you can add a text field in the same way so clients can enter their Skype handle if they choose this option.

Use this process for each option you’d like to provide including using a video chat plugin right on your site or even the option to meet at your office, if you have one.

Once you’re done, click the “Save Settings” button at the bottom of the page and you’ll end up with several options listed in this section.

Custom additional fields are set including the fields "Meet me on Google Hangout," "Google Profile link," "Meet me at your office" and "Meet me here on this site."
You can choose the way your clients meet with you, but this is an example of what your additional fields would look like if you have many meeting options.

Here’s what these options will look like once a client has selected a time slot on your bookings page:

The custom additional fields are shown when booking a consultation on the front end.
You can add as many options as you like and they don’t need to be limited to locations, either. I have even included a custom additional field to allow my clients to describe what they’d like to cover in their appointment.

In the “Payments Settings” you’ll see the option to select a confirmation page from a dropdown list. This is where you would select the one you created.

In the “Notification Settings” area we can elect to send confirmation emails to your clients once consultations are booked. This is where you can customize the email they receive to include all the information they need, including where exactly to meet.

You can add HTML to the confirmation email message to keep things professional. Here’s an example of what you could write for your confirmation emails:

You can also send a similar message in a reminder email in this same section on the settings page. You can also set the time the reminders are set out such as 24 hours before the consultation.

And that’s it! Save your settings and head over to your bookings page. You can give it a test run and see if there’s anything you’d like to change, including making any CSS tweaks to your theme.

Adding a Shopping Cart

If letting your clients book multiple consultations at one time is a feature you need, it’s simple to add by also installing our MarketPress eCommerce plugin, which fully integrates with Appointments +.

It will allow you to turn a consultation into a product that can be purchased in any quantity with a shopping cart.

Once it’s installed, activated and set up, head over to the Appointments + settings. Under “Payment Settings,” you’ll see a section dedicated to MarketPress. All you need to do is select the checkbox “Integrate with MarketPress” and adjust the other settings as you desire.

The MarketPress options within the Appointments + plugin settings. The checkbox for "Integrate with MarketPress" is selected.
You can choose to create an online shop-style page with all your consultations listed by checking the “Create an Appointment Product Page” or you can create your own page, style it how you desire and add the shortcodes you need.

To add a consultation, go to Products > Create New in the admin dashboard and add the Appointments + shortcodes you need to the editor. Select all the other options you’d like such as categories, tags and a title and hit “Publish.”

Unfortunately, allowing clients to purchase consultation packages in not yet possible with MarketPress, but this idea has been submitted as a feature request for a future release. In the meantime, you could offer a coupon instead.

Once you’ve followed these steps, your first consultation will be up and running and your clients will be able to book as many of them as they like and pay for them all at once, unless you have a free appointment option.

Conclusion

With these setup tips, your clients will be able to book consultations with you and your business on their own and it will be fully automated, saving you and your clients a lot of time.

If you would like to add the option to email customers after a consultation at a time of your choosing, check out this featured request thread where the code you need to make it happen is given by an amazing WPMU DEV user name Judah: Appointments +: Send an email to a client after an appointment to follow up.

If you’re looking for more ways to better communicate with your clients, you might also find this post particularly helpful: 16 Plugins to Help You Communicate With Your Users.

Did these setup tips work for you? Share your experience in the comments below.

]]> http://premium.wpmudev.org/blog/streamline-client-consultations/feed/ 8 WordPress Tutorials http://premium.wpmudev.org/blog/add-menus-to-wordpress/ http://premium.wpmudev.org/blog/add-menus-to-wordpress/#comments Mon, 23 Feb 2015 13:00:05 +0000 http://premium.wpmudev.org/blog/?p=137609 Sometimes you may find an awesome theme only to realize it would be great if it had an extra navigation menu with important or frequently used links to increase the usability of your WordPress site.

With just a little bit of coding you could have the foundation of your new menu set up quickly, and ready for you to style to match your theme.

If you would rather not mess around with code, there are many plugins that can do the heavy lifting for you, and also provide styling options.

No matter which option you choose, the guide below will help you make it happen.

Basic Housekeeping

To create a new menu you need to edit your theme files. Before making changes to any of your core files, it’s best to backup your entire site in case something goes wrong along the way. You’ll be able to restore your site quickly and it will be as though nothing ever happened.

You can manually backup your site via FTP or using a plugin, such as our very own Snapshot or something like BackWPup. Just be sure you save a copy of both your database and files in a location separate to your site to minimize the risk of losing your backup.

Creating New Menus

To add a selectable menu location option in your admin dashboard under Appearance > Menus you need to do what’s called “register a menu.” All it takes is adding a snippet of code to your functions.php file located in wp-content > themes > your-theme.

In cPanel, click on the File Manager icon in the Files section on the homepage. It will appear if you haven’t previously disabled the directory selection pop-up.

Choose the Web Root radio button or you can specifically choose the site you wish to edit by selecting Document Root on the list.

After selecting the "File Manager" icon on the cPanel home page, a pop up appeared and a selection has been made for the document root of a specific site.
If you manage many sites from a single cPanel account, selecting the site you want to edit from the “Document Root” option in the directory selection can save you a bit of time navigating through your files.

Locate your functions.php file and click on it once followed by clicking the Edit button at the top of the page.

If a pop-up opens, simply click the Edit button at the bottom, right-hand side. You may not see one if you have previously disabled it.

Scroll to the bottom of the file. If you’d like to add only one menu, add the following code on a new line:

In this example, New Menu is the name that will appear in your admin dashboard’s menu page to make it understandable for human eyes. The new-menu name is what WordPress will understand to execute your code properly.

You can call your menu whatever you like, but make sure only the human-readable name contains spaces and capital letters.

If you would like to add multiple menus to your site, add this code on a new line instead:

You can add as many new menus as you’d like with this method. The same rules will apply when naming them.

Save the changes you made to the file. Now all that’s left is adding the new menu to your site.

Adding Menu Locations to Your Theme

This is where you need to decide where you’d like to place your menu. If you’d like your menu to appear at the top of your page, you’ll need to edit the header.php file. You can also put it in your footer which means you would edit the footer.php file.

You can even display a menu on a page by editing its template file or to a sidebar, editing its sidebar.php file.

You can place your new menu where ever you’d like. Here’s the minimum amount of code you need to add to any of these locations:

Just replace new-menu with WordPress-readable name you chose. You probably want to style your menu with CSS so it goes beyond basic functionality and also looks great. To do this, you’ll need to create a class and add it to your theme with the following code.

Just like before, replace new-menu with the name you chose. In this example, I named the class I created new_menu_class. You can change this, but just be sure to update this code to reflect the adjustment.

Hit the Save button and head over to Appearance > Menus in your dashboard. You’ll notice your new menus will be listed under Theme Locations in the Menu Settings section.

The newly created menus are now visibly listed under "Menu Settings" in the dashboard under Appearance > Menus.
You’ll now be able to see your new menu locations listed. When you add a menu, you can select one or all of the locations.

To have links displayed in your newly made menu locations, click create a new menu at the top of the page.

The "create a new menu" link at the top of the "Menus" page under "Appearance" in the dashboard.
Once you have created a new menu, you can also manage the locations where they are displayed under the “Manage Locations” tab.

Styling, Plugins and Responsive Menus

Your new menu is now ready to be styled using CSS. The coding required is specific to the theme you’re using so I won’t go into it in this post, but we do have another post you can check out for that called How to Create an Awesome Responsive Menu for Your WordPress Theme. It also shows you how to create responsive menus that are mobile-ready.

If you would like an easier option, there are many plugins that will create responsive menus based on your theme’s styles. The best ones I found were Responsive Menu and Suppamenu Lite.

Some notable mentions you may also find helpful are ShiftNav, WP Responsive Menu and Max Mega Menu.

You now have the solid foundation you need to create additional menus for your theme and resources to help you go further.

What kind of menus would you like to create? Feel free to share them in the comments below.

]]>
http://premium.wpmudev.org/blog/add-menus-to-wordpress/feed/ 5
WordPress Tutorials http://premium.wpmudev.org/blog/fixing-password-empty-wordpress-chrome-error/ http://premium.wpmudev.org/blog/fixing-password-empty-wordpress-chrome-error/#comments Sat, 21 Feb 2015 13:00:16 +0000 http://premium.wpmudev.org/blog/?p=137608 WordPress errors can be frustrating, but there are usually ways to solve them. One such error involves the WordPress login screen and Google Chrome.

Some users trying to access their WordPress admin panel have found that Google Chrome seemingly auto-fills their password. Hooray for technology! But once they click submit, they get a message along these lines:

ERROR: The password field is empty.

It’s annoying but fixable. Several months ago, StackExchange user Robbert offered three different ways to put this problem in the past. In this post, I’ll go over each of those options so that you can finally ditch this error.

What’s Going On?

Robbert explains that the error stems from the fact that WordPress’s native code interferes with Chrome’s function to fill in your password.

A bit of JavaScript called wp_attempt_focus initiates after the page loads. It simply clears the form so that you have to enter your login credentials yourself.

Chrome, however, automatically fills in your password. It does so in the instant before WordPress clears the form, so Chrome fails to recognize that the form is, in fact, cleared. That’s why it still displays filled-out fields, implying that your password is good to go.

It’s just a mirage though – in reality, your password is gone. Hence when you hit submit, that irksome error pops up.

Now let’s take a look at the three fixes for this issue.

1. Add and Remove a Space Each Time

This is the simplest way to deal with the error, although I should note that it means you’ll have to make sure to follow this step every single time you log in.

All you need to do is click on the password field, after the password, then add a space and delete it. That’s it.

Doing this turns your password from “fake” to “real,” letting you log in.

Doing this every single time can be a hassle, especially if you log into your site regularly. But it can be useful in many instances where you can’t edit your site’s PHP, which the other fixes I’m going to discuss rely on. If you’re having the problem on a blog other than your own, like a client’s site, for instance, this is a viable solution.

2. Edit Your PHP (The Easy Way)

If you can edit your site’s PHP and want to do so, then there’s a relatively easy fix.

Since wp_attempt_focus operates only when a form is error-free, you can just add a smidgen of PHP to simulate an error and prevent the JavaScript from causing you problems in the first place.

All you need to do is edit your theme’s functions.php to add these lines of code:

3. Edit Your PHP (The More Advanced Way)

The one problem with the above solution is that it prevents wp_attempt_focus from working at all, which you might not want to do. If you disable it completely, WordPress will no longer automatically focus on your form.

If you want to avoid that, you can go into functions.php and edit the code to look like this:

This will avoid the password error and give you autofocus, the best of both worlds.

Conclusion

That’s it – three simple ways to solve the “password field is empty” error with WordPress in Google Chrome. Depending on your needs and abilities, one of these solutions should work for you.

Were you able to fix the error? How long has this been bothering you? Let us know in the comments below.

]]> http://premium.wpmudev.org/blog/fixing-password-empty-wordpress-chrome-error/feed/ 4 WordPress Tutorials http://premium.wpmudev.org/blog/creating-wordpress-admin-pages/ http://premium.wpmudev.org/blog/creating-wordpress-admin-pages/#comments Fri, 20 Feb 2015 13:00:32 +0000 http://premium.wpmudev.org/blog/?p=137222 Admin pages are the heart and soul of plugins.

It’s easy to assume they are complex form-filled monsters, the sole purpose of which is to gather data from the user. The truth is, admin pages provide a familiar place to welcome new users, provide information, and display details for support and documentation.

In this short tutorial we’ll take a look at the basics of how to add these pages to the backend of WordPress. You can then combine this knowledge with other tutorials to create tabbed pages, AJAX functionality, overlays and more.

The Components of an Admin Page

There are two or three components to an admin page, depending on the functionality you are building:

  1. A menu entry – top-level or sub-level
  2. The page content
  3. Processing logic for forms – if needed

For the purposes of this tutorial we will not be looking at forms and form processing, we’ll leave that for another day. Right now what we’ll be concerned with is how to put the pages themselves into place.

Top-Level and Sub-Level Menus

There are two types of menu entries: Top-level and sub-level. I recommend – as does the WordPress Codex – that you think about whether your plugin really needs a top-level menu entry. Too many plugins add top-level entries, which end up polluting the admin heavily.

WordTwit

One example is WordTwit, which tweets new content. It is a great plugin, but it adds a top-level entry unnecessarily.

This is completely unnecessary, an entry in the settings section would do just fine. Some plugins like WooCommerce, bbPress and others add top level items validly; it really depends on how users interact with your product.

A good rule of thumb is: If users need to interact with your plugin daily you can use a top-level entry. If your admin page is just for settings, a sub-level entry in the Settings top-level menu is more appropriate.

Creating a Top-Level Admin Page

The first step is to create a menu entry with the add_menu_page() function. Here’s a full example, explanation ensues:

The function takes seven arguments. The first one is the page title, which defines the title tag; it is shown in the tab title, not on screen.

The second argument is the title that shows up in the menu.

Argument three is the capability required to access the menu. This can be used to restrict it to only admins, editors or authors.

Argument four is the menu slug, which is essentially used as the URL of the page.

Argument five is the function, which will handle the content of the page.

The next argument is the icon url. This can accept a number of formats. If a URL to an image is given the image will be used. You can also use Dashicons, which are built into WordPress, or even SVG.

The last argument defines where the menu will be placed. Argument five indicated the posts so I’ve used six to put this menu entry just underneath. Take a look at the Codex to see exactly what number to use for your desired position.

The next step is to create some content. All you need to do is create the function defined in argument five and echo some content. Here’s a very simple example you can start with:

Creating a Sub-Level Admin Page

There are quite a few functions you can use to add sub-level pages. The general add_submenu_page() will let you put sub-level entries anywhere, but all built-in top level pages have their own functions:

  • To add a menu item under posts use add_posts_page
  • To add a menu item under pages use add_pages_page
  • To add a menu item under media use add_media_page
  • To add a menu item under links use add_links_page
  • To add a menu item under comments use add_comments_page
  • To add a menu item under appearance use add_theme_page
  • To add a menu item under plugins use add_plugin_page
  • To add a menu item under users use add_users_page
  • To add a menu item under tools use add_management_page
  • To add a menu item under settings use add_options_page

Each of these functions follow the same format: add_comments_page( $page_title, $menu_title, $capability, $menu_slug, $function);. The arguments should be familiar from our top-level example above.

You may want to add a sub-level menu to your own top level, in which case these specific function won’t be of much use to you. You’ll need to use add_submenu_page(). Let’s use this function to add an entry under our top level one created above:

As you can see this function is almost identical to the specific functions above, except for the first argument which specifies the slug of the parent element. In our case, this is myplugin/myplugin-admin-page.php.

Conclusion

As you can see, adding menu entries and displaying content is quite easy. The difficulty starts once this has been done. What to put on the page, how to arrange it, using Javascript and CSS to make the presentation great, making sure forms are secure and validated etc. These are things we’ll be taking a look at in future tutorials.

The goal of this article is to give you an understanding of the basics of menu and admin page creation so you can refer back to it when needed. Hopefully you can now create pages for your products. We’ll be tackling specific use-cases in another article soon.

Are there any specific use-cases you would like us to put together? Let us know in the comments below.

]]>
http://premium.wpmudev.org/blog/creating-wordpress-admin-pages/feed/ 1
WordPress Tutorials http://premium.wpmudev.org/blog/bulk-edit-images/ http://premium.wpmudev.org/blog/bulk-edit-images/#comments Wed, 18 Feb 2015 13:00:38 +0000 http://premium.wpmudev.org/blog/?p=137224 If you oversee the management of your WordPress content, you’ll know how time-consuming it can be to manage and edit library images to your preferred size.

They might need to fit your page and its content sufficiently, or you could have style guidelines that your blog posts need to adhere to. Perhaps you’ve recently moved blogs or changed themes and need to update the images to reflect the new style.

At one stage, we were forced to edit our images one at a time – what a chore! But with some clever WordPress tools and a little research and imagination, we can now edit them in bulk as well. This can be through a plugin that enables bulk-editing capabilities, or through embedding a specific code into your chosen images to format them how you’d like.

There are many free and paid-for options out there, but what’s best for you? It depends on your current level of WordPress knowledge and what you’ll use the plugins for. For instance, someone who wants to simply speed up their bulk-editing of a weekly blog post worth of images won’t have the same requirements as a site admin who manages the image content on a daily basis.

Here we will cover some of the best methods out there for bulk-editing your images using WordPress, thus improving your ability to edit quickly and saving you time and money. Check out the following plugins, designed to make your image-editing experience fast and easy.

  • Simple Image Sizes

    Simple Image Sizes

    Let’s start off with a tool that lives up to its name – this really is a simple tool for resizing your images. You can override your theme sizes directly on the media options page and resize images individually or in bulk.

  • WP Media Category Management

    WP Media Category Management Plugin

    This plugin was recently upgraded to include toggle switches for every image in your library, allowing you to shut images on and off as well as toggling bulk images for multi-media support. The recent update also enabled the support of taxonomies that have been set by other plugins that may be in use, eliminating plugin antagonism and cutting back on confusion for the user.

    Features of this plugin include:

    • Implement the use of short code (brand new or in existence) to filter specific post and media gallery content.
    • Use post or dedicated media categories freely.
    • Media Library filtering capabilities allow your media lists to be filtered according to your specific tailored taxonomies.
    • Manage your media and post categories in the same fashion.
    • Bulk-toggle any taxonomy used for media directly from your Media Library by means of administration tools.
  • WP Quick Featured Images

    WP Quick Featured Images Plugin

    This plugin will assist you in speedily bulk-editing your images, with a focus on featured images and thumbnails. Thumbnails are an essential part of your media usage and site marketing strategy and Quick Featured Images allows you to quickly manage these images right from your WP dashboard.

    • It has flexible filters, allowing you to choose which images you’d like to add, replace or remove.
    • You can easily see which thumbnails have been used across all posts and pages through its sortable image column.
    • You can set rules to define automatic default featured images present.
  • Media Library Assistant

    Media Library Assistant

    This is another popular plugin that has proven itself very effective when it comes to bulk editing posts and images. The Media Library Assistant will provide the following:

    • Provides the user with over 20 listing columns.
    • Provides [mla_gallery] shortcode, which is used in a post or page to provide an entire gallery of images to use and edit as needed.
    • Provides [mla_tag_cloud] shortcode for your gallery items, keeping the most frequently used images ready at your fingertips.
    • Provides more filters for taxonomy and MIME types you may be using.
    • Full support for all taxonomies you are using.
    • Gives you the ability to un-attach pieces, as well as edit the post_parent and menu_order.
    • A ‘bulk-edit’ section, which allows you to tailor your fields, as well as update authorship and administrative duties.
    • Provides you with more information regarding the parent of every attachment.
    • Quick-edit capabilities.
    • ‘Where-use’ allows you to view which images have been used with which posts, as well as where and when they were used.
    • ‘Content Templates’ give you the ability to put together a valuation from a wide variety of information resources, conduct testing, and mix text in with your media.
    • ‘Search media’ enhancement provides you with powerful image search capabilities.
    • PDF, IPTC, and EXIF (including GPS) metadata can be easily assigned to specific fields and taxonomy terms.
    • Integrates well with other gallery plugins.
    • All-inclusive control over MIME types, file upload extensions, and icon images that are file-type.
    • Metadata attachments regarding the size of a file, where it is used, and its dimensions, can be freely assigned.

    This download covers just about everything and is widely popular among WordPress users who put out a large amount of content.

  • Custom Bulk/Quick Edit

    Custom Bulk Quick Edit Plugin

    Custom Bulk/Quick Edit gives you the ability to add fields that are completely customizable to your needs on a very simple and speedy basis. You can edit the bulk-images you use and you are provided with quick-edit panels to make things even easier for you. It also allows you to reset your taxonomy, radio, and checkbox options (resetting current bulk-editing options), and edit post metas that are associated with checkboxes, radio, and text area fields. Plus it allows for tag taxonomies and category editing in bulk as well.

    While this is a pretty good plugin, providing you with the ability to take care of your bulk-editing needs fairly quickly and easily, it is important to note that in order to download and use the plugin itself you must first buy Custom Bulk/Quick Edit Premium.

  • Bulk Re-Size Media

    bulk resize media

    This plugin makes it super-easy to resize large images or batch files in a few quick clicks. It is easy to navigate and is dependable for pulling your images through nicely, plus it will save a lot of time and money if you deal with high volumes of media content on a consistent basis. It also integrates with multisite so your administrators can maintain the site control they need. Other features of this plugin include:

    • BMG to JPG optional file conversion capabilities.
    • Auto-resizing of uploaded images (the maximum size will be maintained in the file).
    • Network administrators working with MultiSite are able to dictate image size for the entire configuration.
    • Specify the size of particular attachments to certain items with the bulk resize feature.
    • Allows quality and size to be easily configured.

    This plugin is pretty straightforward as far as bulk-editing goes, and it is perfect for users of multiSite, making admin duties far easier.

  • NextGEN Gallery

    nextgen-gallery

    NextGEN Gallery boasts the title of being the most popular WordPress gallery plugin, along with one of the most popular WordPress plugins of all time with over 10 million downloads. So what’s so good about this plugin?

    It has many features to manage your gallery of images, including the ability to bulk upload and resize thumbnails across one or more galleries. Watermarks can be added to whole galleries of images.

    Individual images can also be edited, including the meta data and image tags. You can choose between a slideshow gallery or thumbnail, which is just one example of the flexibility built into this plugin.

  • WP Meta SEO

    wp-meta-seo

    This plugin was born out of the frustration of not being able to edit all meta content and image meta data. As well as being able to bulk resize the images, WP Meta SEO prides itself on bulk editing all website meta through an intuitive interface and optimizing the wrong image size.

    Features include:

    • Bulk image resizing.
    • Reduce the page weight by fixing the image size.
    • Optimize images in all your post and pages.
    • Edit an image’s file name in single view.
    • Image date filtering.
    • Automatic AJAX saving.
    • Yoast SEO import and sync.
    • Alexa world rank.
    • Meta content filtering.
    • Live Google snippet preview.

Image Optimizers

If you want to reduce the size of your images across your site purely to reduce bandwidth and make your website load faster, you might consider an optimization plugin.

With a faster loading website, your readers or customers will be more satisfied. Plus, Google has included website speed as part of its search ranking algorithm. So it’s really kind of important.

Image optimizers allow you to decrease the image size by around 90% without compromising the quality of the image or website performance. Most optimize your images in bulk and support many file types, such as JPEG, PNG, and GIF (including animated). They usually back up the original images in a folder on your hosting servers in case you ever want to restore them. Choose between lossy compression for photographs, or lossless compression for animated images and technical drawings.

Image optimizers for WordPress include:

Shortcode and Bulk-Editing

Many of the plugins and updates you install for bulk editing purposes will have shortcode embedding capabilities. This is the planting of a code within a specific media during the bulk-editing process for resizing, editing, and posting purposes.

If you use a plugin that is a bit simpler in its structure and the features it offers, the use of automatic shortcode may not be an option. It’s therefore a good idea to investigate other options rather than amend the code yourself, particularly as functionality may not remain if you change themes or amend other areas of your site.

There are some great free options available and it’s worth taking the time to learn their features to personalize your site as well as save yourself some editing time.

Plugins that can be used through the WordPress interface and allow quick and easy creation of WordPress shortcodes and TinyMCE rich editor buttons include J Shortcodes, or Shortcodes UI for those who don’t have any coding knowledge or experience.

One way to force your images into the size and location you want is by removing the date path from specific media files and grouping them together in one intended folder. This method of bulk-editing does not require a plugin download and is fairly easy to implement, but some developers suggest it’s a data loss risk. If you’re using multisite, the following should make this a snap:

Go to yourdomain.com/wp-admin/network/sites.php

Click on Edit > Settings. Then look for Uploads Use Yearmonth Folders. You’ll want to change this to 0.

Final Thoughts

If your bulk image editing is a slow process and you find it is really costing you time and money, you’ll be happy to know there are other options out there.

The plugins covered above are some of the most effective and easy-to-use available for bulk image editing with WordPress, allowing you to pick up the pace on your content distribution.

Whether you’re a coding whizz or WordPress novice, plugins make this often laborious task a whole lot easier. If you are more on the expert side of the scale, investigating the shortcode plugin options is a good idea so that you can personalize the way you manage your site’s content. You could also go straight into the site and amend the code, but remember to back up your site first!

What are your favorite plugins or shortcode options for bulk-editing images? Have you had experience in using the ones we’ve mentioned? Let us know in the comments below. 

]]>
http://premium.wpmudev.org/blog/bulk-edit-images/feed/ 2
WordPress Tutorials http://premium.wpmudev.org/blog/mastering-wp-query/ http://premium.wpmudev.org/blog/mastering-wp-query/#comments Tue, 17 Feb 2015 13:00:37 +0000 http://premium.wpmudev.org/blog/?p=137375 Getting posts from the WordPress database is one of my favorite topics. The flexibility of the WP_Query class – which allows you to do this – is awesome, it enables all the fancy CMS-like features you see on the front-end.

Do you need to list all tasks entered by a certain user between two specific dates? No problem! Do you want to list all scheduled posts and pages in a specific category, but only if it was modified less than two weeks ago? You can do that, too!

The WP_Query class is easy to understand and easy to implement. In this comprehensive tutorial – complete with lots of example code snippets – we’ll look at how you can use the class to make WordPress do your bidding.

What is a WordPress Query?

Let’s back up a bit and talk about queries. In general, when someone says query they mean a query to the database – we ask it for some information. This can be anything from all the phone numbers of all our users to all the categories created.

When referring to “a query” or “a WordPress query” we usually mean a query that retrieves some posts for us. Almost all WordPress pages create a query for you on their own. On the index page (the main blog view) WordPress queries the database for your latest posts. On a category archive page the latest posts within the category are retrieved. On author pages the latest posts from the author are pulled, and so on.

Even single posts and single pages use a query. In those cases they always return one result, but query it is nevertheless. So almost any default page you load contains a query that is performed automatically.

The Loop: How Queries Are Used

It’s one thing to retrieve a bunch of posts, and it’s a whole other matter to actually display them. Each theme uses different HTML and styling elements to do this, but what they all share is “the loop.” The loop simply refers to a WordPress mechanism that steps through the retrieved posts, enabling themes to display them. It looks something like this:

OK, so this isn’t just a loop, it’s also an if/else statement. It is a simplified example of what you might find on any page which lists a bunch of posts. First we use have_posts() to check if any posts are returned. Then, as long as there are posts we create an element for them and output the title and the content. The the_post() function is responsible for processing some more post data and incrementing the counter. At the end we display some text if there are no posts to show.

Before we move on, let’s clarify some terminology. The term “the loop” is used to describe the loop on the page which lists the posts pulled in by WordPress by default. Let’s look at an example to clarify this. If you scroll to the bottom of an article right here on WPMU DEV, you’ll see a related articles section:

related articles
Related articles on our blog.

This section lists posts and uses a custom query and a loop to do so. This is not considered “the loop,” however, because the items within it aren’t the ones WordPress lists by default on this page. If you have multiple queries and loops on the same page they are usually referred to as secondary loops and custom queries.

Creating Our First Query

Let’s create our first custom query. Let’s say we want to list posts from a particular author in a particular category. Here’s one way to do that:

The first part of the code above deals with querying a database. As you can see I’ve instantiated a new WP_Query object by passing it some arguments. Don’t worry if you don’t understand the fancy object oriented terminology here because using it is very straightforward. I passed my user’s nicename as the author_name parameter and the category’s slug as the category_name parameter.

To list these posts we need to modify our loop slightly. Instead of using have_posts() and the_post() we use them as methods of the WP_Query object. What this means in practice is prepending $variable_name-> before these functions.

In future examples I won’t show the loop but the idea is always the same. If our variable is called $custom_posts you’ll need to use $custom_posts->have_posts() and $custom_posts->the_post(). Easy-peasy.

WP_Query Parameters

Creating custom queries is all about using the parameters. How to get posts from particular dates, authors, custom post types, custom taxonomies, statuses and more. Let’s take a look at all the parameters with some basic examples for each.

Author Parameters

There are four separate parameters you can use to grab authors. The author parameter accepts a single author ID or a comma separated list of author IDs. Using negative numbers will result in that author ID being excluded.

author_name is a parameter you can use if you want to pass the author’s nicename instead if his/her ID. Take care as this is not necessarily the same as his/her username.

The two remaining author-related parameters are author__in and author__not_in. These were added later in WordPress 3.7 enabling much-needed array support. With their help you can supply your author needs as arrays.

This doesn’t seem like much of a change from using the author parameter but from a modularization and best practices point of view it is a world apart.

Use Case: Listing Articles From Top Authors

Let’s take a look at how you could approach listing articles by top authors. Let’s assume that you have a rating system in place. Each author’s global rating is stored in the user meta table with the key of rating. We can combine the get_users()function and a custom loop to grab the posts of authors with the highest ratings.

Category Parameters

Restricting posts based on categories can be done with no less than five separate functions. The cat parameter behaves just like the author parameter from above, accepting integers to include and negative integers to exclude:

The category_name is horribly named because it actually accepts a category slug. You can usually guess a slug from the name by converting all letters to lowercase, omitting all special characters apart from underscores and dashes and turning spaces into dashes. A category named “Book Reviews” will likely have the slug: “book-reviews.”

You can use arrays of categories with three parameters. category__in and category__not_in behave just like their author counterparts. In addition to these you can use category__and, which will make sure that only posts that are assigned all categories given are retrieved.

Use Case: Get Articles from Your Most Used Categories

In this scenario we’ll retrieve a list of categories based on the item count within that category. We’ll feed this to our query to get posts from the top 3 most frequently used categories.

Tag Parameters

You’d think that tags would have the same set of arguments, and you would almost be right, but there are two extra here.

Since tag, tag_id, tag__and, tag__in and tag__not_in should be familiar by now, let’s look at some quick examples:

I’d like to point out two things. First of all, the WordPress core is inconsistent. category expects an ID, tag expects a slug, category_name actually expects the slug and so on. The takeaway here is that you should always strive to make things as consistent as possible but everyone makes mistakes. Sometimes you are forced to make them for legacy reasons, for example. Take criticism with a pinch of salt!

The second thing I wanted to point out was that you should always use array when possible. Even though the tag parameter allows you to handle multiple tags, I recommend using tag__in and the other array-based ones.

To make things even easier tags have an additional two parameters: tag_slug__and and tag_slug__in. Apparently there is no tag_slug__not_in. Don’t ask why! These behave as you would expect them to:

Use Case: Combining Tags, Categories And Authors

Since we know a few parameters now, why not start combining them? Let’s take two specific authors and show everything they’ve written that has been featured (by adding the “featured” tag to it) in the “Books” or “Movies” category.

Post Types

WordPress has a number of built-in post types: post, page, attachment, revision and navigation menu item. It has become commonplace to add custom post types for managing projects, your portfolio, products, forums and so on. Using the custom post type parameter post_type you can narrow down your posts based on post type.

When a string is passed to this parameter it will look for posts with the given post type only. If an array of post types is passed, posts will be returned for any matching post types.

Note that this parameter has a default value, which is post. If you want to return other post types you must specify them explicitly. If you are using the tax_query parameter (more on this later) the default value becomes any.

Post Status

Just like we did for post types we can specify a single post status or multiple post statuses to pull posts from. The post_status parameter takes a string if a single status is used or an array if you want to select from more than one. WordPress has eight built-in statuses:

  • publish – a published post or page.
  • pending – post is pending review.
  • draft – a post in draft status.
  • auto-draft – a newly created post, with no content.
  • future – a post to publish in the future.
  • private – not visible to users who are not logged in.
  • inherit – a revision. see get_children.
  • trash – post is in trashbin (available with Version 2.9).

You can use any to indicate that you want to include all post statuses. The default is publish. Make sure to specify if you want something else.

Use Case: Sneak Peeks Of Upcoming Products

If you run a bookstore and you know that a potential bestseller is coming out soon you could use a custom WordPress query to list them. No need to publish these posts and then use some special trickery to exclude them from view until they can be ordered, just list scheduled posts directly:

The Search Parameter

The horribly named s parameter takes a string, which is used to search within your posts. Make sure to URL encode your search string (you can use PHP’s urlencode function) to account for spaces and other special characters.

Use Case: Searching Post Subsets

A search of your whole content can be performed from the default search widget so using the s parameter is most useful when combined with other parameters. The following examples allow you to search various subsets of posts:

Password Protected Posts

In the publishing settings box you can choose to password protect a post. This is great for protecting private content or building a subscription model, perhaps. Whatever the case may be, you can use the has_password parameter to specify whether or not you want password protected posts listed.

If the value of this parameter is true the query will grab posts that have passwords associated with them. If false you will get only those posts that do not have passwords. If the parameter is set to null or omitted all posts will be shown. You can use the post_password to list posts that are protected by a specified password.

Use Case: Online Treasure Hunt

You can create a fun game using WordPress. Users must de-cypher a puzzle, getting a password for a list of posts, which contain clues to the final solution. The user must put the password in a form. Once submitted it takes the user to a page, which uses the submitted password as a query parameter, something like this:

By using the full loop from the beginning of the post you can make sure the user gets a “no posts found” message if the incorrect password is given. If the correct one has been entered, a list of posts will be shown protected by that password.

Including, Excluding and Targeting Specific Posts

There are nine separate parameters for grabbing one or more specific posts. p is the parameter you can use to grab one specific post-based on its ID. To use a page slug you can pass a string to the name parameter. page_id and pagename accomplish the same task, but for pages these two parameters are a bit confusing. If you pass the ID of a page to the p parameter, it will not work! On the other hand, even if you don’t set post_type specifically, page_id will work as expected.

Think of it like this: When you use p or name it is as if the post type was set to post. When you use page_id and pagename it is as if the post type was set to page.

The post__in and post__not_in params work similarly to the ones we saw for categories and tags. They accept an array of post IDs.

The post_parent parameter takes a single ID. Only posts, which are child posts of the given ID, will be listed. The post_parent__in and post_parent__not_in parameters take an array of post IDs – we’re used to this convention by now.

Keep the post type restrictions in mind when using these parameters. If you include the IDs of multiple post types you will need to specify any as the post type, or the exact types you are looking for.

Use Case: Get All Post Attachments

If you’d like to list all images and other attachments of a post you can use the parent parameter to your advantage. This is perfect for auto-generating galleries or download lists.

Taxonomy Queries

Now that you have a good understanding of parameters and how they are used, it’s time to look at a more advanced one: tax_query.

This parameter is itself an array, which you can use to create more complex conditions and use custom taxonomies. Let’s take a look at it through an example, courtesy of the WordPress Codex.

Our taxonomy query has two conditions and a relation. The relation dictates whether at least one condition (OR), or all conditions (AND) must be true. The conditions themselves are arrays that define the taxonomy restrictions.

The first condition states that the posts we are looking for must have the movie genre action or comedy assigned. The second condition states that we are looking for all posts, except for those associated with the three listed actors.

Since both conditions must be true (due to the AND restriction), this query will result in all action and comedy movies that star actors other than the ones listed.

Each condition has five parameters of its own:

  • taxonomy – where you specify the taxonomy slug
  • field – choose between term_id, name or slug
  • terms – use a single integer or string or an array of integers or strings
  • operator – how multiple terms are handled. IN will allow posts belonging to any of the listed terms. NOT IN will allow any posts that don’t include any of the listed terms. AND will only allow posts that include all of the listed terms>
  • include_children – Wether or not to include children for hierarchical taxonomies

Use Case: Advanced Content Filtering

Taxonomy filters have a wide range of uses. From dealing with custom product taxonomies to creating an IMDB-style movie database you can do a lot with them. Here’s another example that allows for advanced book filtering:

In this particular case the user wants to view all books which are a bit more upbeat (don’t contain the negative tags we’ve given) but they can’t be from the comedy or romance genres.

Meta Queries

Meta queries are similar to taxonomy queries in structure. They allow you to query posts based on their values in the post meta table. WordPress offers four parameters here which can be used (meta_key, meta_value, meta_value_num and meta_compare) but can be substituted with meta_query which is far better. Let’s look at an example:

This example shows a meta query which returns books that are over 500 pages in length, the syntax is quite easy after the taxonomy query. Let’s look at the subparameters you can use to specify what you want:

  • key – The key of the custom field
  • value – The value you are looking for
  • compare – The value comparison operator. Possible values are ‘=’, ‘!=’, ‘>’, ‘>=’, ‘<‘, ‘<=’, ‘LIKE’, ‘NOT LIKE’, ‘IN’, ‘NOT IN’, ‘BETWEEN’, ‘NOT BETWEEN’, ‘EXISTS’, and ‘NOT EXISTS’
  • type – The data type of the field. Possible values are ‘NUMERIC’, ‘BINARY’, ‘CHAR’, ‘DATE’, ‘DATETIME’, ‘DECIMAL’, ‘SIGNED’, ‘TIME’, ‘UNSIGNED’

Don’t forget the relation parameter, which you can use to indicate the relationship between the separate query clauses – it works just like in the taxonomy queries above.

Use Case: Posts With Featured Images

There are tons and tons of ways to use meta queries. One great example is grabbing only posts with featured images. The ID of the featured image is stored in the post meta table using the _thumbnail_id key. We can use a meta query to check for posts where the value of this meta key is not empty.

Date Queries

Dates have a similar history to meta queries. WP_Query offers 8 parameters to narrow down your post list by date, all of which can be replaced with the date_query. I’ll be looking at date_query exclusively because using it is better practice.

Date queries can be a bit more complex, let’s look at the parameters before we get into the examples. Here is the full list, courtesy of the WordPress Codex:

  • year – 4 digit year (e.g. 2011).
  • month – Month number (from 1 to 12).
  • week – Week of the year (from 0 to 53).
  • day – Day of the month (from 1 to 31).
  • hour - Hour (from 0 to 23).
  • minute – Minute (from 0 to 59).
  • second – Second (0 to 59).
  • after – Date to retrieve posts after. Accepts strtotime()-compatible string, or array of ‘year’, ‘month’, ‘day’ values:
    • year Accepts any four-digit year. Default is empty.
    • month The month of the year. Accepts numbers 1-12. Default: 12.
    • day The day of the month. Accepts numbers 1-31. Default: last day of month.
  • before – Date to retrieve posts before. Accepts strtotime()-compatible string, or array of ‘year’, ‘month’, ‘day’ values:
    • year Accepts any four-digit year. Default is empty.
    • month The month of the year. Accepts numbers 1-12. Default: 1.
    • day The day of the month. Accepts numbers 1-31. Default: 1.
  • inclusive – For after/before, whether exact value should be matched or not.
  • compare – See WP_Date_Query::get_compare().
  • column – Column to query against. Default: ‘post_date’.
  • relation – OR or AND, how the sub-arrays should be compared. Default: AND.

That’s a bit of a mouthful but it does allow us to use dates with considerable flexibility. By using the first seven parameters you can target date ranges all in one go:

To have more control over date ranges you can use the before and after parameters. You’ll need to specify the year/month-day as sub-array members. Use the inclusive parameter in conjunction to specify wether or not the boundaries should be taken into account.

This example (from the Codex) will return all posts between January 1st 2013 and February 28, 2013. Since inclusive is set to true, posts on the boundary date will also be returned.

Date functionality here is based on the WP_Date_Query class. I recommend giving it a read for a more thorough understanding – it can do quite a lot!

Use Case: Seasonal Past Posts

Many websites have seasonal content: Christmas posts, New Year’s roundups, Valentines Day stuff and so on. By using a custom date query you can add relevant time-sensitive content to your website from your archives.

The short example below will pull posts from April 1st, spreading April fool’s cheer perhaps?

Pagination

I wouldn’t blame you for thinking that we’ll be looking at one parameter here or perhaps two. In reality there are no less than seven parameters for handling pagination.

The most basic one you will probably use is posts_per_page, which essentially determines the number of posts to pull from the database. Setting it to -1 will grab all available posts.

paged is a frequently used parameter, it determines which page of results show. It is used in conjunction with posts_per_page. If 10 posts are shown per page and the paged parameter is set to 4 your fourth set of 10 posts will be returned. nopaging allows you to ignore paging completely if it is set to true.

You may also find yourself in need of the offset parameter which works just like an offset in MySQL – it offsets the posts retrieved by the given amount. This tends to break pagination unless you know what you’re doing, I would use this sparingly.

If you find yourself bothered by sticky posts you can use ignore_sticky_posts to ignore them. By default sticky posts are placed at the top of the list, as well as the natural location they would be in. To disable this behaviour set this parameter to false.

The posts_per_archive_page parameter sets how many pages are shown on archive pages. These would be all pages where the is_archive() and is_search() functions return true. If this parameter isn’t used the posts_per_page parameter is used.

Finally, the page parameter shows the posts that would normally show up just on page X of a Static Front Page.

The example above returns the second set of 20 posts from the database while ignoring sticky posts.

Ordering Results

When listing your results, the order in which they are shown is just as important as what is returned. Two parameters give you control over this: order and orderby.

The orderby parameter determines the order in which posts are returned. There are quite a few options, let’s take a look:

  • none – No order (natural MySQL selection order)
  • ID – Order by post id
  • author – Order by author id
  • title – Order by title
  • name – Order by post slug.
  • type – Order by post type
  • date – Order by date
  • modified – Order by last modified date
  • parent – Order by parent id
  • rand – Random order
  • comment_count – Order by number of comments
  • menu_order – Order by Page Order
  • meta_value – Order by the meta value
  • meta_value_num – Order by numeric meta value
  • post__in – Preserve order given in the post__in parameter

Almost all of these are self explanatory, let’s take a more detailed look at ordering posts by meta value. To get this to work you need to specify the meta_key parameter as well so WordPress knows which key to pull meta values for. You should also take care to specify the correct type since ordering lead to unexpected results otherwise.

if you are ordering regular text you should be fine. If you are ordering numeric values, use meta_value_num instead of meta_value. Alternatively you can specify the meta_type parameter which allows you to specify the data type. See the meta_query section for data types you can use.

Finally, the order parameter determines the direction of the ordering. Use ASC for ascending, DESC for descending. Take a look at the examples below for a practical look at how ordering can be done for various use cases.

For the sake of thoroughness I thought I’d mention the option to order by multiple columns. Pre 4.0 you could do this using a space separated value for the orderby parameter, like this: orderby => 'title menu_order'. Since WordPress 4.0 this was improved, you can now use an array and specify the order separately:

Use Case: Order Products By Price

A frequently needed feature in eCommerce themes is the ability to order products by price. In the example below we look for products over $20 and list the results by price, lowest to highest:

Returning Values

It seems that the fields parameter is not well-known, even though it is one of the most useful features. You can pass two values to this parameter or omit it. If omitted you will end up with post objects as usual. If you pass ids an array of post IDs will be returned. If you pass id=>parent an associative array of ID – parent relationships will be returned.

The reason I think this is such a useful feature is optimization. Some plugins use WP_Query to grab post IDs for galleries or other shortcodes. Many do not utilize the return parameter and end up giving the server a lot more work to do – work which is never used in the code. If you just need IDs make sure to use the fields parameter.

Use Case: Programmatically Placing A Gallery

If you want a gallery after each of your posts, showing all the images in that post you can utilize a query in tandem with the gallery shortcode.

First, we grab all attachments from the post, making sure to return the IDs only. We then implode this array to make a string containing a comma separated list of IDs we can use in the shortcode. Finally we use do_shortcode() to create the gallery.

Permission

This one is a bit obscure and not implemented very modularly. The idea is that if you use the perm parameter and supply readable as the value, only posts which the current user can read will be shown. This is useful if you want to list regular and private posts but make sure to only list those private posts that the user has access to.

Caching

This one is for advanced optimization – it allows you to control the caching behaviour of queries. Generally it is a good idea to add results of a query to the cache, chances are it will be used again and again in the same form. Your list of top 10 posts is not likely to change from query-to-query for example.

There are two cases where you may want to control what is cached. If you list posts without needing their metadata or taxonomy data you can use update_post_meta_cache and update_post_term_cache to disable the respective cache. If you are just doing a one-off query for a quick test you can also use cache_results to disable caching of the post results themselves.

One instance where I’ve used this was creating a quick export table of all the posts in the database. The export was essentially a CSV file of all post IDs, titles, categories and tags associated with the posts. Caching this one-off query makes no sense, especially since there were 8,000 posts with lots and lots of meta data.

WP_Query Properties

So far we’ve been looking at the parameters we can pass to WP_Query. Since we are talking about a class here, not a simple function there are properties and methods we can use to manipulate it. The WP_Query Properties Documentation has a full list of properties. I’ll show you some of the more useful ones and how to use them, in case you aren’t familiar with properties.

I personally tend to use $query_vars, $found_posts, $post_count and $max_num_pages. $query_vars holds the array that was passed to the class, it contains all the parameters we used when making our query.

The $found_posts property holds the number of posts found in total that match our query. The $post_count property holds the number of posts currently being shown. These are usually not the same since pagination is being used. There may be 52 posts found, but only 10 are displayed currently.

Beware as the $post_count is also not necessarily the same as the value used in the posts_per_page argument. If 52 posts are found and 10 are shown per page the last page will look like this: 52 posts found, 10 posts displayed per page but currently, only two are being shown.

Finally, $max_num_pages holds the number of pages needed to display the results. This is basically the result of $found_posts / $posts_per_page rounded up to the next whole number.

WP_Query Methods

When talking about classes, properties are just like variables, methods are just like functions. WP_Query has a number of methods, although you won’t really need to use them directly in most cases. The two most important ones you already know are have_posts() and the_post(). Take a look back at the beginning of the article for how these work.

There are some useful functions like rewind_posts() which essentially resets the loop. You may want to use this if you are outputting the exact same list in two separate locations.

The get() and set() methods allow you to get and set a specific query variable. Again, these are usually not used by themselves only in special circumstances. Take a look at the Method Documentation for more information.

Data Safety: Validating, Sanitizing And Escaping

Custom queries are frequently paired with front-end forms. A typical scenario may be a custom-coded filter system allowing the user more access over the post list. Take a look at our Adding Post Filters To Your WordPress Site article for an introduction.

If you are accepting any form of user input you should always escape the data to prevent SQL injection attacks and other headaches. Take a look at the excellent Validating, Santitizing And Escaping User Data article in the Codex for more information about this topic.

Modifying the Raw SQL Query

There are a number of filters that allow you to hook into the actual SQL query that is performed upon the use of WP_Query. This is rarely needed so do try and work with the given parameters. More often than not (way more often) you can do everything you need since this class is pretty powerful.

Filters such as posts_where and posts_join allow you to modify specific clauses in your SQL statement. While WP_Query is flexible, it doesn’t currently allow for very complex WHERE clauses involving multiple taxonomies and multiple relations. In these cases you could use these filters to modify the query directly.

The WP_Query Filters section is a good place to start but you will need considerable SQL knowledge to utilize these filters properly.

Wrapping Up

This article hopefully gave you a better understanding of the WP_Query class and just how useful it is when dealing with post lists. Its use doesn’t stop at listing posts – you can combine the class with custom post types, taxonomies and meta data to build a powerful and useful CMS system.

If you’re interested, there are a few classes which work similarly or are used within WP_Query and other sections of WordPress. WP_Comment_Query can be used to grab comments in much the same way as WP_Query. WP_Meta_Query handles all the meta queries and WP_Date_Query handles all the date restrictions for both classes and will probably be used in upcoming parts of the WP ecosystem.

]]>
http://premium.wpmudev.org/blog/mastering-wp-query/feed/ 4
WordPress Tutorials http://premium.wpmudev.org/blog/uninstall-multisite/ http://premium.wpmudev.org/blog/uninstall-multisite/#comments Sun, 15 Feb 2015 13:00:00 +0000 http://premium.wpmudev.org/blog/?p=137599 WordPress Multisite is a powerful solution for launching several websites off just one WordPress install.

While it’s relatively straightforward to set up, uninstalling it can be a challenge for the uninitiated.

In this Weekend WordPress Project, I’ll show you how to quickly uninstall Multisite and get your site back to running a single WordPress install.

Uninstalling Multisite

Removing Multisite involves undoing all of the work you did to install it in the first place. Let’s go through it step by step:

Backup Your Site

It’s always better to be safe than sorry. Check out our Snapshot plugin if you don’t already have your own method of backing up.

Edit wp-config File

Login to your WordPress site via FTP or cPanel, whichever method you prefer. If you’re using cPanel, go to File Manager to access your site’s files.

Open your wp-config.php file and delete the following code:

You will also need to edit the following line in your wp-config.php file and set it to “false”:

Edit .htaccess File

Next, you will need to edit your .htaccess file, which is in the root of your WordPress install. Replace the rules you added to create your Multisite install with the following new rules:

Drop Database Tables

Lastly, you will need to drop the following global tables in your database. phpMyAdmin is probably the easiest software to do this with if you use cPanel, though you can use whatever method you like:

  • wp_blogs
  • wp_blog_versions
  • wp_registration_log
  • wp_signups
  • wp_site
  • wp_sitemeta

The next time you log in to your site Multisite should be gone from your WordPress install.

Wouldn’t it be easier if there weren’t so many steps for installing and uninstalling Multisite? Let us know what you think in the comments below.

]]>
http://premium.wpmudev.org/blog/uninstall-multisite/feed/ 0
WordPress Tutorials http://premium.wpmudev.org/blog/display-wordpress-post-page-ids/ http://premium.wpmudev.org/blog/display-wordpress-post-page-ids/#comments Sat, 14 Feb 2015 13:00:07 +0000 http://premium.wpmudev.org/blog/?p=137171 Every now and again it would be convenient to know the ID of a post or page in WordPress, right?

Whether it’s for a shortcode, when setting something up in the theme settings, or maybe just to get a quick link.

Whatever the case may be, WordPress doesn’t make it easy to figure out a post’s ID. One way to grab it is to visit the edit page of a post and check out the URL. It should look something like this:

https://yourwebsite.com/wp-admin/post.php?post=137171&action=edit

The 137171 in the example above is the ID of the post – the main identifier in the database. Surely there must be an easier way to figure it out right? Fortunately, there is.

Display Post IDs with a Plugin

The easiest solution is to use a plugin. The granddaddy is Reveal IDs, a free plugin that clocks in at just over 425,000 downloads.

Another new option is WPsite Show IDs.

Both plugins do just about the same thing: show the ID of posts, pages, users, categories, custom taxonomies, custom post types and so on. The only reason I lean toward WPsite Show IDs is the 8Kb footprint. Reveal Ids is around 311Kb, which seems a bit excessive for such a simple plugin.

DIY: Display Post IDs with Code

If you’re interested in how to display post IDs yourself, let’s take a look at the code.

The code below should go inside a plugin or your theme’s functions file. If you would like to create a plugin, take a look at our guide to plugin development for a simple template.

Before we get started, it’s also worth saying you should create a child theme. Check our our guide to child themes if you’re not already familiar with how to create one.

Adding Custom Columns

WordPress offers great tools to modify admin post lists, including creating your own columns and content. We’ll need to use a filter to add the column and an action to add the values. Let’s do a quick test on the regular posts table:

That is all we need. The filter allows us to add a column by modifying the columns array. The array key should be the identifier for the column and the value will be displayed as the header text.

The function hooked to the action takes two parameters: the column name and the id of the post being shown. This is perfect – we make sure to simply echo the ID when our custom column is shown.

The “revealid” function is my attempt at a pun, sorry about that! It is meant as a prefix for all our functions to make sure they don’t collide with other plugins.

A quick aside: Note how I used 'revealid_id' == $column, which seems a bit alien. This is called a Yoda condition and is preferred in WordPress. The reasoning is that if you forget to define the variable you won’t get a huge gaping PHP error on your page.

Here’s what it looks like in the backend of WordPress:

Displaying post IDs

Finding the Right Hooks

The two functions above are all we will need. The remaining piece of the puzzle is where to hook them in. The hooks we used target regular posts only and our IDs will not show up for pages or other elements.

In reality, these hooks are called variable hooks because they belong to a standardized set. The common form is: manage_[post_type_or_element]_columns and manage_[post_type_or_element]_custom_column.

Based on this, posts, pages, media and custom post types should be easy, since these are all post types. To make IDs show up for all these elements you can use the following hooks:

Small caveat here: Everything except posts and pages uses the post types. The post type for posts is technically “post,” the post type for pages is “page.” For some reason the hooks use the plural form. This is a WordPress quirk since it really should be the singular form. See, even the WordPress core isn’t perfect.

I’ve added a custom post type in there: project. What if you want to apply this to all custom post types? In that case you can cycle through all of them easily like so:

I recommend the same approach when dealing with taxonomies. To output the ID for categories only you could use manage_edit-link-categories_columns and manage_link_categories_custom_column but to add it to all taxonomies we need to use another loop:

Last but not least we have users and comments. These are fairly straightforward as well. Take a look:

Placing the ID in Front

This small change is a bit more difficult than it seems. When we added the ID column we appended it to the end of an existing array containing all the other columns. The solution seems easy enough: Add it to the front. We could do this by merging arrays but it turns out that the checkbox is the first column – we actually want the ID in second place.

We’ll still use array merge but we need a bit more trickery – we need to split it up first. The first array will contain the checkbox (the first element of the original array), the second array will contain everything else. We will merge the first array with an array containing our ID and then with the second array. The code should make this a lot clearer:

Conclusion

I think this is a great example of the modularity of WordPress. IDs were once shown in the admin (pre-WordPress 2.5) but it turned out not many people needed them. Once this feature was removed, plugins sprang up to cater to those who still wanted to see the post IDs.

Writing our own plugin provides a glimpse of how modular WordPress is and how easy it is to modify the admin itself. The same method outlined above could be used to add thumbnails, description snippets and other information to the admin list table.

If you’ve added something awesome to an admin list, or have an idea you’d like to see added to it, do let us know in the comments below.

]]>
http://premium.wpmudev.org/blog/display-wordpress-post-page-ids/feed/ 3