Tag Archives: techniques (wp)

Three Approaches To Adding Configurable Fields To Your WordPress Plugin


Anyone who has created a WordPress plugin understands the need to create configurable fields to modify how the plugin works. There are countless uses for configurable options in a plugin, and nearly as many ways to implement said options. You see, WordPress allows plugin authors to create their own markup within their settings pages. As a side effect, settings pages can vary greatly between plugins.

In this article we are going to go over three common ways you can make your plugin configurable. We will start by creating a settings page and create our fields using the default WordPress Settings API. I will then walk you through how to set up your fields with a custom handler. Finally, I will show you how to integrate a great configurable fields plugin Advanced Custom Fields (ACF) into your own plugin.

The post Three Approaches To Adding Configurable Fields To Your WordPress Plugin appeared first on Smashing Magazine.

Originally from – 

Three Approaches To Adding Configurable Fields To Your WordPress Plugin

Building An Advanced WordPress Search With WP_Query


Many WordPress superpowers come from its flexible data architecture that allows developers to widely customize their installations with custom post types, taxonomies and fields. However, when it comes down to its search, WordPress provides us with only one-field form that often appears inadequate and leads site admins to adopt external search systems, like Google Custom Search, or third-party plugins.

Building An Advanced Search System in WordPress with WP_Query

In this article I’ll show you how to provide your WordPress installation with an advanced search system allowing the user to search and retrieve content from a specific custom post type, filtering results by custom taxonomy terms and multiple custom field values.

The post Building An Advanced WordPress Search With WP_Query appeared first on Smashing Magazine.

Link: 

Building An Advanced WordPress Search With WP_Query

How To Create And Customize A WordPress Child Theme


The WordPress platform is a magnet for those who want to take matters into their own hands, who want complete control over their websites and want to be independent in running them. WordPress does make it really easily to completely customize a website. If you have a bit of knowledge of HTMl, CSS and/or PHP, there is nothing you can’t change.

How To Create And Customize A WordPress Child Theme

I mean, just compare the default themes, Twenty Fifteen and Twenty Fourteen. Hard to believe they are running on the same platform, isn’t it? Therefore, it is only natural for you to want to adapt the look of your website to fit your vision. I doubt there are many WordPress users out there who don’t constantly think about what to implement next. However, a problem arises.

The post How To Create And Customize A WordPress Child Theme appeared first on Smashing Magazine.

Read More:

How To Create And Customize A WordPress Child Theme

Useful Tips To Get Started With WordPress Hooks


Even though hooks in WordPress are amazing and everyone uses them knowingly or unknowingly, I get the impression that some advanced users and especially front-end developers still seem to avoid them. If you feel like you’ve been holding back on hooks, too, then this article will get you started. I am also going to reveal some interesting details to anyone who thinks they are familiar enough with hooks.

Hooks in WordPress

You’ll want to read this article especially if you’d like to: understand code snippets with hooks such as those found in forums, extend WordPress, plugins and themes without breaking updates, learn how to avoid common problems, allow others to extend your code.

The post Useful Tips To Get Started With WordPress Hooks appeared first on Smashing Magazine.

Continue reading:  

Useful Tips To Get Started With WordPress Hooks

Customizing Tree-Like Data Structures In WordPress With The Walker Class


In WordPress, a navigation menu, a list of categories or pages, and a list of comments all share one common characteristic: They are the visual representation of tree-like data structures. This means that a relationship of superordination and subordination exists among the elements of each data tree.

WordPress Comments Structure

There will be elements that are parents of other elements and, conversely, elements that are children of other elements. A reply to a comment depends logically on its parent, in the same way that a submenu item depends logically on the root element of the tree (or subtree).

The post Customizing Tree-Like Data Structures In WordPress With The Walker Class appeared first on Smashing Magazine.

Continue reading: 

Customizing Tree-Like Data Structures In WordPress With The Walker Class

Extending Advanced Custom Fields With Your Own Controls


Advanced Custom Fields (ACF) is a free WordPress plugin that replaces the regular custom fields interface in WordPress with something far more powerful, offering a user-friendly interface for complex fields like location maps, date pickers and more.

Extending Advanced Custom Fields With Your Own Controls

In this article I’ll show you how you can extend ACF by adding your own controls to tailor the experience to your needs.

The post Extending Advanced Custom Fields With Your Own Controls appeared first on Smashing Magazine.

Credit: 

Extending Advanced Custom Fields With Your Own Controls

How To Deploy WordPress Plugins With GitHub Using Transients


If you’ve worked with WordPress for a while, you may have tried your hand at writing a plugin. Many developers will start creating plugins to enhance a custom theme or to modularize their code. Eventually, though, you may want to distribute your plugin to a wider audience.

Deploy WordPress Plugins With GitHub Using Transients

While you always have the option to use the WordPress Subversion repository, there may be instances where you prefer to host a plugin yourself. Perhaps you are offering your users a premium plugin. Maybe you need a way to keep your client’s code in sync across multiple sites. It could simply be that you want to use a Git workflow instead of Subversion. Whatever the reason, this tutorial will show you how to set up a GitHub repository to push updates to your plugin, wherever it resides.

The post How To Deploy WordPress Plugins With GitHub Using Transients appeared first on Smashing Magazine.

Read article here: 

How To Deploy WordPress Plugins With GitHub Using Transients

Thumbnail

Rapid Front-End Prototyping With WordPress

Prototyping is one of the best things that can happen within a project, yet it is extremely underutilized. Prototyping makes a project better suited to users, elevates user experience, increases the quality of your final code, and keeps clients happy.

The problem is that developers often see prototyping as a waste of time, since high-quality prototypes take considerable effort to make. I want to show you that by using WordPress, highly interactive prototypes with great visuals are not at all that difficult to make.

Rapid Front-end Prototyping With WordPress1
(Image credit: Jeff Sheldon via Unsplash2) (View large version3)

First, we’ll look at some basic prototyping concepts, then set up a test server from scratch. We’ll continue by converting an HTML template to a WordPress theme and learning how to use its items to create what we need. We’ll also learn how to add front-end and server-side functionality to our prototype.

While all this seems complex, beginners should be able to follow along easily, including the “create your own server” section, which is a cinch!

About Prototyping

“[A] prototype is an early sample, model, or release of a product built to test a concept or process or to act as a thing to be replicated or learned from.”

Wikipedia4

This sentence neatly sums up the pros and cons of a prototype. The advantage of creating a prototype is that it lets you test an idea and learn from the process. It allows you to make a reasonable assumption about the feasability of your project before you put in hundreds of hours of work.

One of the downsides is that prototypes are made so that we may learn from them. Often, designers and coders look on this as wasted time. Why make a protoype when we could be working on the real thing? Who is going to pay us for the time we spend prototyping?

To be honest, these are tricky questions. For smaller projects, no one will pay you for it, but your project will be better for it; this, in turn, leads to bigger and better projects. In most cases, the time you spend prototyping is regained while building the product anyway!

It also appears that designers like to prototype a lot more than developers. The root of the issue here is speed. A designer could prototype a design a lot faster than a developer, since the latter needs to build a quick framework, implement a design and do a lot of fiddly things which take time.

Fidelity And Functionality

We can approach prototypes by looking at two key features: fidelity and functionality. Fidelity refers to how detailed the prototype is visually, while functionality refers to the level of interaction possible within the system. Let’s look at how levels of fidelity and functionality in prototypes pair up.

Low-Functionality, Low-Fidelity

These prototypes are easy to make. They could be simple drawings, or Balsamiq mock-ups5. There is minimal interaction — or none at all — and visually the prototype has very little to do with the final product.

A Balsamiq mock-up of Facebook6
A Balsamiq mock-up of Facebook. (Image credit: Frontify7)(View large version8)

Low-Functionality, High-Fidelity

Increasing the fidelity while keeping functionality low is also quite common. A good example would be a Photoshop design file which could contain final design elements. Again, there is next to no interaction here but plenty of visual detail, enough to put it close to the final product in terms of design.

A high-quality PSD mock-up of notifications9
A high-quality PSD mock-up of notifications. (Image credit: Pixeden10)(View large version11)

High-Functionality, Low-Fidelity

These prototypes are a bit more difficult but you can still make them without too much effort. Before you create the login/forgot password form for a large website, you might want to test if everything works by just dropping in a form and business logic strictly in HTML and PHP — no CSS, JavaScript or consideration of the context of the form.

Twitter without any CSS12
Twitter without any CSS. (View large version13)

Using front-end frameworks like Bootstrap14 or Foundation15 can can increase your fidelity somewhat, but you’d need to write a good amount of CSS to make it your own.

A medium fidelity mock-up16
A medium fidelity mock-up. (Image credit: Bootstrap17)(View large version18)

I would still consider these low-fidelity mock-ups because each front-end framework looks generic by default. That’s fine for testing the principle, but it doesn’t increase fidelity to a point where more sensitive clients would be able to visualize what the final product will be like.

High-Functionality, High-Fidelity

Prototypes like this are rarely seen because creating them can take more time than is worth it. Why create something so similar to the website-to-be when you could be working on the actual site?

High-functionality, high-fidelity prototypes contain a high degree of interactivity while also being a much closer facsimile of the final product. Users can follow links, submit forms and do many other things that help them see what the end result will be like.

The real trick is managing the time spent on making such prototypes — which is where WordPress comes in.

Which One To Use

There is, of course, no simple answer to this question. A high-fidelity, high-functionality prototype is closest to the real thing, but it takes time to make; for simpler projects, it may not be worth the time.

Low-fidelity, low-functionality prototypes are simplistic and cannot be interacted with, but for small projects and close-knit teams, perhaps they’re all that is needed.

Several factors need to be considered:

  • How well your team works together
  • How large your project is
  • How visually and technically oriented your client is
  • How well you understand the product you are building
  • How many people will be involved other than programmers and designers

In my experience, the most important factors are the client and the project’s complexity. Even if I understand the project well, I would like a high-fidelity, high-functionality prototype just in case. One of the fundamental mistakes you can make in projects is thinking you know them well.

For complex, large-scale projects you should always create prototypes with a high degree of freedom. The more systems and subsystems you need to build, the more intertwined they become and the more places things can go wrong.

The client can be an even bigger factor. Often, clients do not know what they want. They may not be design- or code-oriented, which means they will equate a low-fidelity prototype with bad design and missing features — even if you tell them what the prototype is for. As a result, a clearer visual aid is sometimes called for to enhance communication.

Since I will be talking about high-fidelity and high-functionality prototypes from now on, I will be calling them high-quality prototypes. This is not at all a reflection on other prototypes; a low-fideltiy, low-functionality prototype can also be created with high quality.

Considerations For High-Quality Prototypes

There are a number of considerations when making high-quality prototypes. What platform they should be built on, what functions need to be added (or not added), how intricate should we make the design, and so on.

The Platform

The platform chosen should be one which allows you to work fast and quickly add features as well. Bootstrap, Foundation and other frameworks are great, but they offer very little functionality, since they are purely front-end. Using them can still be a good idea, but not on their own.

On the other side of the spectrum, we have PHP frameworks like Laravel, which is excellent for creating high-quality modular code. This is out of the question, though, since we have to write too much business logic ourselves just to get a site up and running.

WordPress strikes a good balance here because it is essentially a bag of useful functions combined with a reasonably flexible way to template pages quickly. I want to stress that you should use a platform you feel comfortable with. If you’re amazing at using Laravel, by all means go with it.

The Design

You can create a simple design framework for yourself, but that also takes quite some time. This is the place to use front-end frameworks to lighten your workload.

What I recommend is getting a good pre-made HTML admin template. Many of these templates use Bootstrap or Foundation anyway, and put a bunch of elements at your fingertips. In addition, they’ve already styled the elements of their frameworks into something less generic, which is just what we need. With a little work they can be converted to WordPress themes and will facilitate extremely quick prototyping.

I don’t use bespoke WordPress themes because they are for presenting content, not creating application architecture. You won’t be able to create a menu or a form anywhere easily, and your code will likely be a mess by the end.

Depth Of Functionality

Depth of functionality is all about interactivity. Since you have control over a CMS you can, in theory, make things work properly — login forms could genuinely log you in. You probably don’t want to spend your time coding in all the functionality. That isn’t really the point here.

For example, is the login form really important? Everyone knows how logging in works. Perhaps the form can be allowed to be blank, and the login button logs you in immediately as a test user.

If you are building a finance management app, however, you may want to spend some time making sure that the “Add transaction” form works as expected. Real data can be listed and submitted adding a great deal of depth to your prototype.

Prototyping With WordPress

I think WordPress is a great choice for prototyping because of the flexibility of templating and the number of functions you have at your disposal. Logging in and out, adding metadata, querying items — a lot of base functionality is already there.

I like to choose a pre-made HTML admin theme that looks close to what we’ll be doing in the final iteration of the design. You can find a large number of premium admin themes on Themeforest19 but you can also grab some good free ones via a quick Google search. For my examples I will be using a free admin theme called AdminLTE20.

When choosing an admin theme try to gauge what features you will need. Concentrate on the rapid aspect of prototyping, not making sure that your prototype looks like the final design.

A Complete Example

When I started this article, I wanted to provide a complete example of how I use WordPress to prototype. I ended up recording a video of the process and writing about it in a bit more detail. The video below will walk you through my process of creating a prototype of the Twitter front page.

Following the video I’ll go into even more detail, giving you some instruction about setting up test servers, using the WordPress menu system to populate menus, and much more. I recommend watching the video first, and then looking at the details below, as they will be a lot clearer.

Footnotes

  1. 1 http://www.smashingmagazine.com/wp-content/uploads/2015/06/01-featured-opt.jpg
  2. 2 https://unsplash.com/ugmonk
  3. 3 http://www.smashingmagazine.com/wp-content/uploads/2015/06/01-featured-opt.jpg
  4. 4 https://en.wikipedia.org/wiki/Prototype
  5. 5 ‘https://balsamiq.com/products/mockups/’
  6. 6 http://www.smashingmagazine.com/wp-content/uploads/2015/06/02-balsamiq-facebook-opt.png
  7. 7 https://frontify.com/blog/discuss-specify-balsamiq-mockups/
  8. 8 http://www.smashingmagazine.com/wp-content/uploads/2015/06/02-balsamiq-facebook-opt.png
  9. 9 http://www.smashingmagazine.com/wp-content/uploads/2015/06/03-notifications-psd-opt.jpg
  10. 10 http://www.pixeden.com/psd-web-elements/psd-notification-ui-box/
  11. 11 http://www.smashingmagazine.com/wp-content/uploads/2015/06/03-notifications-psd-opt.jpg
  12. 12 http://www.smashingmagazine.com/wp-content/uploads/2015/06/04-twitter-opt.png
  13. 13 http://www.smashingmagazine.com/wp-content/uploads/2015/06/04-twitter-opt.png
  14. 14 ‘http://getbootstrap.com/’
  15. 15 ‘http://foundation.zurb.com/’
  16. 16 http://www.smashingmagazine.com/wp-content/uploads/2015/06/05-bootstrap-opt.png
  17. 17 http://getbootstrap.com/examples/jumbotron-narrow/
  18. 18 http://www.smashingmagazine.com/wp-content/uploads/2015/06/05-bootstrap-opt.png
  19. 19 ‘http://themeforest.net’
  20. 20 http://shapebootstrap.net/item/adminlte-dashboard-and-control-panel/

The post Rapid Front-End Prototyping With WordPress appeared first on Smashing Magazine.

More: 

Rapid Front-End Prototyping With WordPress

A Detailed Guide To WordPress Custom Page Templates

I like to think of WordPress as the gateway drug of web development. Many people who get started using the platform are initially merely looking for a comfortable (and free) way to create a simple website. Some Googling and consultation of the WordPress Codex1 later, it’s done and that should be it. Kind of like “I’m just going to try it once.”

However, a good chunk of users don’t stop there. Instead, they get hooked. Come up with more ideas. Experiment. Try out new plugins. Discover Firebug2. Boom. Soon there is no turning back. Does that sound like your story? As a WordPress user it is only natural to want more and more control over your website. To crave custom design, custom functionality, custom everything.

Luckily, WordPress is built for exactly that. Its flexible structure and compartmentalized architecture allows anyone to change practically anything on their site.

Among the most important tools in the quest for complete website control are page templates. They allow users to dramatically alter their website’s design and functionality. Want a customized header for your front page? Done. An additional sidebar only for your blog page? No problem. A unique 404 error page? Be. My. Guest.

If you want to know how WordPress page templates can help you achieve that, read on. But first, a little background information.

Template Files In WordPress

What are we talking about when we speak of templates in the context of WordPress? The short version is that templates are files which tell WordPress how to display different types of content.

The slightly longer version: every time someone sends a request to view part of your website, the WordPress platform will figure out what content they want to see and how that specific part of your website should be rendered.

For the latter, WordPress will attempt to use the most appropriate template file found within your theme. Which one is decided on the basis of a set order, the WordPress template hierarchy3. You can see what this looks like in the screenshot below or in this interactive version4.

The WordPress template hierarchy.5
The WordPress template hierarchy. (Image credit: WordPress Codex6)(View large version7)

The template hierarchy is a list of template files WordPress is familiar with that are ranked to determine which file takes precedence over another.

You can think of it as a decision tree. When WordPress tries to decide how to display a given page, it works its way down the template hierarchy until it finds the first template file that fits the requested page. For example, if somebody attempted to access the address http://yoursite.com/category/news, WordPress would look for the correct template file in this order:

  1. category-slug.php: in this case category-news.php
  2. category-id.php>: if the category ID were 5, WordPress would try to find a file named category-5.php
  3. category.php
  4. archive.php
  5. index.php

At the bottom of the hierarchy is index.php. It will be used to display any content which does not have a more specific template file attached to its name. If a template file ranks higher in the hierarchy, WordPress will automatically use that file in order to display the content in question.

Page Templates And Their Use

For pages, the standard template is usually the aptly named page.php. Unless there is a more specific template file available (such as archive.php for an archive page), WordPress will use page.php to render the content of all pages on your website.

However, in many cases it might be necessary to change the design, look, feel or functionality of individual parts of your website. This is where page templates come into play. Customized page templates allow you to individualize any part of your WordPress site without affecting the rest of it.

You might have already seen this at work. For example, many WordPress themes today come with an option to change your page to full width, add a second sidebar or switch the sidebar’s location. If that is the case for yours, it was probably done through template files. There are several ways to accomplish this and we’ll go over them later.

First, however, a word of caution: since working with templates involves editing and changing files in your active theme, it’s always a good idea to go with a child theme when making these kinds of customizations. That way you don’t run the danger of having your changes overwritten when your parent theme gets updated.

How To Customize Any Page In WordPress

There are three basic ways to use custom page templates in WordPress: adding conditional statements to an existing template; creating specific page templates which rank higher in the hierarchy; and directly assigning templates to specific pages. We will take a look at each of these in turn.

Using Conditional Tags In Default Templates

An easy way to make page-specific changes is to add WordPress’s many conditional tags8 to a template already in use. As the name suggests, these tags are used to create functions which are only executed if a certain condition is met. In the context of page templates, this would be something along the line of “Only perform action X on page Y.”

Typically, you would add conditional tags to your theme’s page.php file (unless, of course, you want to customize a different part of your website). They enable you to make changes limited to the homepage, front page, blog page or any other page of your site.

Here are some frequently used conditional tags:

  1. is_page(): to target a specific page. Can be used with the page’s ID, title, or URL/name.
  2. is_home(): applies to the home page.
  3. is_front_page(): targets the front page of your site as set under Settings → Reading
  4. is _category(): condition for a category page. Can use ID, title or URL/name like is_page() tag.
  5. is_single(): for single posts or attachments
  6. is_archive(): conditions for archive pages
  7. is_404(): applies only to 404 error pages

For example, when added to your page.php in place of the standard get_header(); tag, the following code will load a custom header file named header-shop.php when displaying the page http://yoursite.com/products.

if ( is_page('products') ) 
  get_header( 'shop' );
 else 
  get_header();

A good use case for this would be if you have a shop on your site and you need to display a different header image or customized menu on the shop page. You could then add these customization in header-shop.php and it would show up in the appropriate place.

However, conditional tags are not limited to one page. You can make several statements in a row like so:

if ( is_page('products') ) 
  get_header( 'shop' );
 elseif ( is_page( 42 ) ) 
  get_header( 'about' );
 else 
  get_header();

In this second example, two conditions will change the behavior of different pages on your site. Besides loading the aforementioned shop-specific header file, it would now also load a header-about.php on a page with the ID of 42. For all other pages the standard header file applies.

To learn more about the use of conditional tags, the following resources are highly recommended:

Creating Page-Specific Files In The WordPress Hierarchy

Conditional tags are a great way to introduce smaller changes to your page templates. Of course, you can also create larger customizations by using many conditional statements one after the other. I find this a very cumbersome solution, however, and would opt for designated template files instead.

One way to do this is to exploit the WordPress template hierarchy. As we have seen, the hierarchy will traverse a list of possible template files and choose the first one it can find that fits. For pages, the hierarchy looks like this:

  • Custom page template
  • page-slug.php
  • page-id.php
  • page.php
  • index.php

In first place are custom page templates which have been directly assigned to a particular page. If one of those exists, WordPress will use it no matter which other template files are present. We will talk more about custom page templates in a bit.

After that, WordPress will look for a page template that includes the slug of the page in question. For example, if you include a file named page-about.php in your theme files, WordPress will use this file to display your ‘About’ page or whichever page can be found under http://www.yoursite.com/about.

Alternatively, you can achieve the same by targeting your page’s ID. So if that same page has an ID of 5, WordPress will use the template file page-5.php before page.php if it exists; that is, only if there isn’t a higher-ranking page template available.

(BTW, you can find out the ID for every page by hovering over its title under ‘All Pages’ in your WordPress back-end. The ID will show up in the link displayed by your browser.)

Assigning Custom Page Templates

Besides providing templates in a form that WordPress will use automatically, it is also possible to manually assign custom templates to specific pages. As you can see from the template hierarchy, these will trump any other template file present in the theme folder.

Just like creating page-specific templates for the WordPress hierarchy, this requires you to provide a template file and then link it to whichever page you want to use it for. The latter can be done in two different ways you might already be familiar with. Just in case you aren’t, here is how to do it.

1. Assigning Custom Page Templates From The WordPress Editor

In the WordPress editor, you find an option field called ‘Page Attributes’ with a drop-down menu under ‘Template’.

Page Attributes in the WordPress editor.11
Page Attributes in the WordPress editor. (View large version12)

Clicking on it will give you a list of available page templates on your WordPress website. Choose the one you desire, save or update your page and you are done.

Available templates under Page Attributes.13
Available templates under Page Attributes. (View large version14)

2. Setting A Custom Template Via Quick Edit

The same can also be achieved without entering the WordPress editor. Go to ‘All Pages’ and hover over any item in the list there. A menu will become visible that includes the ‘Quick Edit’ item.

Click on it to edit the page settings directly from the list. You will see the same drop-down menu for choosing a different page template. Pick one, update the page and you are done.

Not so hard after all, is it? But what if you don’t have a custom page template yet? How do you create it so that your website looks exactly the way you want it? Don’t worry, that’s what the next part is all about.

A Step-By-Step Guide To Creating Custom Page Templates

Putting together customized template files for your pages is not that hard but here are a few details you have to pay attention to. Therefore, let’s go over the process bit-by-bit.

1. Find The Default Template

A good way is to start by copying the template which is currently used by the page you want to modify. It’s easier to modify existing code than to write an entire page from scratch. In most cases this will be the page.php file.

(If you don’t know how to find out which template file is being used on the page you want to edit, the plugin What The File15 will prove useful.)

I will be using the Twenty Twelve theme for demonstration. Here is what its standard page template looks like:

<?php
/**
 * The template for displaying all pages
 *
 * This is the template that displays all pages by default.
 * Please note that this is the WordPress construct of pages
 * and that other 'pages' on your WordPress site will use a
 * different template.
 *
 * @package WordPress
 * @subpackage Twenty_Twelve
 * @since Twenty Twelve 1.0
 */
get_header(); ?>

  <div id="primary" class="site-content">
    <div id="content" role="main">

      <?php while ( have_posts() ) : the_post(); ?>
        <?php get_template_part( 'content', 'page' ); ?>
        <?php comments_template( '', true ); ?>
      <?php endwhile; // end of the loop. ?>

    </div><!-- #content -->
  </div><!-- #primary -->

<?php get_sidebar(); ?>
<?php get_footer(); ?>

As you can see, nothing too fancy here: the usual calls for the header and footer, and the loop in the middle. The page in question looks like this:

The default page template in the Twenty Twelve theme.16
The default page template in the Twenty Twelve theme. (View large version17)

2. Copy And Rename The Template File

After identifying the default template file, it’s time to make a copy. We will use the duplicated file in order to make the desired changes to our page. For that we will also have to rename it. Can’t have two files of the same name, that’s just confusing for everyone.

You are free to give the file any name you like as long as it doesn’t start with any of the reserved theme filenames18. So don’t be naming it page-something.php or anything else that would make WordPress think it is a dedicated template file.

It makes sense to use a name which easily identifies what this template file is used for, such as my-custom-template.php. In my case I will go with custom-full-width.php.

3. Customize The Template File Header

Next we have to tell WordPress that this new file is a custom page template. For that, we will have to adjust the file header in the following way:

<?php
/*
 * Template Name: Custom Full Width
 * Description: Page template without sidebar
 */

// Additional code goes here...

The name under ‘Template Name’ is what will be displayed under ‘Page Attributes’ in the WordPress editor. Make sure to adjust it to your template name.

4. Customize The Code

Now it’s time to get to the meat and potatoes of the page template: the code. In my example, I merely want to remove the sidebar from my demo page.

This is relatively easy, as all I have to do is remove <?php get_sidebar(); ?> from my page template since that’s what is calling the sidebar. As a consequence, my custom template ends up looking like this:

<?php
/*
 * Template Name: Custom Full Width
 * Description: Page template without sidebar
 */

get_header(); ?>

<div id="primary" class="site-content">
  <div id="content" role="main">

    <?php while ( have_posts() ) : the_post(); ?>
      <?php get_template_part( 'content', 'page' ); ?>
      <?php comments_template( '', true ); ?>
    <?php endwhile; // end of the loop. ?>

  </div><!-- #content -->
</div><!-- #primary -->

<?php get_footer(); ?>

5. Upload The Page Template

After saving my customized file, it is now time to upload it to my website. Custom page templates can be saved in several places to be recognized by WordPress:

  • Your active (child) theme’s folder
  • The folder of your main parent theme
  • A subfolder within either of these

I personally like to create a folder named page_templates in my child theme and place any customized templates in there. I find this easiest to retain an overview over my files and customizations.

6. Activate The Template

As a last step, you need to activate the page template. As mentioned earlier, this is done under Page Attributes → Templates in the WordPress editor. Save, view the page and voilà! Here is my customized page without a sidebar:

Customized page template without the sidebar.19
Customized page template without the sidebar. (View large version20)

Not so hard, is it? Don’t worry, you will quickly get the hang of it. To give you a better impression of what to use these page templates for, I will demonstrate additional use cases (including the code) for the remainder of the article.

Five Different Ways To Use Page Templates

As already mentioned, page templates can be employed for many different purposes. You can customize pretty much anything on any page with their help. Only your imagination (and coding abilities) stand in your way.

1. Full-Width Page Template

The first case we will look at is an advanced version of the demo template we created above. Up there, we already removed the sidebar by deleting <?php get_sidebar(); ?> from the code. However, as you have seen from the screenshot this does not actually result in a full-width layout since the content section stays on the left.

To address this, we need to deal with the CSS, in particular this part:

.site-content 
  float: left;
  width: 65.1042%;

The width attribute limits the element which holds our content to 65.1042% of the available space. We want to increase this.

If we just change it to 100%, however, this will affect all other pages on our site, which is far from what we want. Therefore, the first order here is to change the primary div‘s class in our custom template to something else, like class="site-content-fullwidth". The result:

<?php
/*
 * Template Name: Custom Full Width
 * Description: Page template without sidebar
 */

get_header(); ?>

<div id="primary" class="site-content-fullwidth">
  <div id="content" role="main">

    <?php while ( have_posts() ) : the_post(); ?>
      <?php get_template_part( 'content', 'page' ); ?>
      <?php comments_template( '', true ); ?>
    <?php endwhile; // end of the loop. ?>

  </div><!-- #content -->
</div><!-- #primary -->

<?php get_footer(); ?>

Now we can adjust the CSS for our new custom class:

.site-content-fullwidth 
  float: left;
  width: 100%;

As a result, the content now stretches all the way across the screen.

The custom page template at full width.21
The custom page template at full width. (View large version22)

2. Dynamic 404 Error Page With Widget Areas

The 404 error page is where every person lands who tries to access a page on your website that doesn’t exist, be it through a typo, a faulty link or because the page’s permalink has changed.

Despite the fact that getting a 404 is disliked by everyone on the Internet, if you are running a website the 404 error page is of no little importance. Its content can be the decisive factor on whether someone immediately abandons your site or sticks around and checks out your other content.

Coding a customized error page from scratch is cumbersome, especially if you are not confident in your abilities. A better way is to build widget areas into your template so you can flexibly change what is displayed there by drag and drop.

For this we will grab and edit the 404.php file that ships with Twenty Twelve (template hierarchy, remember?). However, before we change anything on there, we will first create a new widget by inserting the following code into our functions.php file:

register_sidebar( array(
  'name' => '404 Page',
  'id' => '404',
  'description'  => __( 'Content for your 404 error page goes here.' ),
  'before_widget' => '<div id="error-box">',
  'after_widget' => '</div>',
  'before_title' => '<h3 class="widget-title">',
  'after_title' => '</h3>'
) );

This should display the newly created widget in your WordPress back-end. To make sure that it actually pops up on the site, you need to add the following line of code to your 404 page in the appropriate place:

<?php dynamic_sidebar( '404' ); ?>

In my case, I want to replace the search form (<?php get_search_form(); ?>) inside the template with my new widget, making for the following code:

<?php
/**
 * The template for displaying 404 pages (Not Found)
 *
 * @package WordPress
 * @subpackage Twenty_Twelve
 * @since Twenty Twelve 1.0
 */

get_header(); ?>

<div id="primary" class="site-content">
  <div id="content" role="main">

    <article id="post-0" class="post error404 no-results not-found">
      <header class="entry-header">
        <h1 class="entry-title"><?php _e( 'This is somewhat embarrassing, isn&amp;rsquo;t it?', 'twentytwelve' ); ?></h1>
      </header>

      <div class="entry-content">
        <?php dynamic_sidebar( '404' ); ?>
      </div><!-- .entry-content -->
    </article><!-- #post-0 -->

  </div><!-- #content -->
</div><!-- #primary -->

<?php get_footer(); ?>

After uploading the template to my site, it’s time to populate my new widget area:

404 page template widget.23
404 page template widget. (View large version24)

If I now take a look at the 404 error page, my newly created widgets show up there:

Customized 404 page.25
Customized 404 page. (View large version26)

3. Page Template For Displaying Custom Post Types

Custom post types are a great way to introduce content that has its own set of data points, design and other customizations. A favorite use case for these post types are review items such as books and movies. In our case we want to build a page template that shows portfolio items.

We first need to create our custom post type (CPT). This can be done manually or via plugin. One plugin option I can wholeheartedly recommend is Types27. It lets you easily create custom post types and custom fields.

Install and activate Types, add a custom post, make sure its slug is ‘portfolio’, customize any fields you need (such as adding a featured image), adjust any other options, and save.

Now, that we have our portfolio post type, we want it to show up on our site. The first thing we’ll do is create the page in question. Be aware that if you chose ‘portfolio’ as the slug of your CPT, the page can not have the same slug. I went with my clients-portfolio and also added some example text.

Portfolio page without a custom page template.28
Portfolio page without a custom page template. (View large version29)

After adding a few items in the ‘portfolio’ post type section, we want them to show up on our page right underneath the page content.

To achieve this we will again use a derivative of the page.php file. Copy it, call it portfolio-template.php and change the header to this:

<?php
/*
 * Template Name: Portfolio Template
 * Description: Page template to display portfolio custom post types 
 * underneath the page content
 */
 

However, in this case we will have to make a few changes to the original template. When you take a look at the code of page.php, you will see that it calls another template file in the middle, named content-page.php (where it says <?php get_template_part( 'content', 'page' ); ?>). In that file we find the following code:

<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
  <header class="entry-header">
    <?php if ( ! is_page_template( 'page-templates/front-page.php' ) ) : ?>
    <?php the_post_thumbnail(); ?>
    <?php endif; ?>
    <h1 class="entry-title"><?php the_title(); ?></h1>
  </header>

  <div class="entry-content">
    <?php the_content(); ?>
    <?php wp_link_pages( array( 'before' => '<div class="page-links">' . __( 'Pages:', 'twentytwelve' ), 'after' => '</div>' ) ); ?>
  </div><!-- .entry-content -->
  <footer class="entry-meta">
    <?php edit_post_link( __( 'Edit', 'twentytwelve' ), '<span class="edit-link">', '</span>' ); ?>
  </footer><!-- .entry-meta -->
</article><!-- #post -->

As you can see, it is here that the page title and content are called. Since we definitely want those on our portfolio site, we will need to copy the necessary parts of this template to our page.php file. The result looks like this:

get_header(); ?>

<div id="primary" class="site-content">
  <div id="content" role="main">

    <?php while ( have_posts() ) : the_post(); ?>
      <header class="entry-header">
        <?php the_post_thumbnail(); ?>
        <h1 class="entry-title"><?php the_title(); ?></h1>
      </header>

      <div class="entry-content">
        <?php the_content(); ?>
      </div><!-- .entry-content -->
      
      <?php comments_template( '', true ); ?>
    <?php endwhile; // end of the loop. ?>

  </div><!-- #content -->
</div><!-- #primary -->

<?php get_sidebar(); ?>
<?php get_footer(); ?>

To get the portfolio items onto our page, we will add the following code right beneath the the_content() call.

<?php
  $args = array(
    'post_type' => 'portfolio', // enter custom post type
    'orderby' => 'date',
    'order' => 'DESC',
  );
   
  $loop = new WP_Query( $args );
  if( $loop->have_posts() ):
  while( $loop->have_posts() ): $loop->the_post(); global $post;
    echo '<div class="portfolio">';
    echo '<h3>' . get_the_title() . '</h3>';
    echo '<div class="portfolio-image">'. get_the_post_thumbnail( $id ).'</div>';
    echo '<div class="portfolio-work">'. get_the_content().'</div>';
    echo '</div>';
  endwhile;
  endif;
?>

This will make the CPT show up on the page:

The custom portfolio template.30
The custom portfolio template. (View large version31)

I’m sure we all agree that it looks less than stellar, so some styling is in order.

/* Portfolio posts */

.portfolio 
  -webkit-box-shadow: 0px 2px 2px 0px rgba(50, 50, 50, 0.75);
  -moz-box-shadow:    0px 2px 2px 0px rgba(50, 50, 50, 0.75);
  box-shadow:         0px 2px 2px 0px rgba(50, 50, 50, 0.75);
  margin: 0 0 20px;
  padding: 30px;

.portfolio-image 
  display: block;
  float: left;
  margin: 0 10px 0 0;
  max-width: 20%;

.portfolio-image img 
  border-radius: 0;

.portfolio-work 
  display: inline-block;
  max-width: 80%;

.portfolio h3
  border-bottom: 1px solid #999;
  font-size: 1.57143rem;
  font-weight: normal;
  margin: 0 0 15px;
  padding-bottom: 15px;

Much better, don’t you think?

The custom portfolio template with styling.32
The custom portfolio template with styling. (View large version33)

And here is the entire code for the portfolio page template:

<?php
/*
 * Template Name: Portfolio Template
 * Description: Page template to display portfolio custom post types 
 * underneath the page content
 */

get_header(); ?>

<div id="primary" class="site-content">
  <div id="content" role="main">

    <?php while ( have_posts() ) : the_post(); ?>
        
      <header class="entry-header">
        <?php the_post_thumbnail(); ?>
        <h1 class="entry-title"><?php the_title(); ?></h1>
      </header>

      <div class="entry-content">
        <?php the_content(); ?>
        <?php
          $args = array(
            'post_type' => 'portfolio', // enter custom post type
            'orderby' => 'date',
            'order' => 'DESC',
          );
              
          $loop = new WP_Query( $args );
          if( $loop->have_posts() ):
          while( $loop->have_posts() ): $loop->the_post(); global $post;
            echo '<div class="portfolio">';
            echo '<h3>' . get_the_title() . '</h3>';
            echo '<div class="portfolio-image">'. get_the_post_thumbnail( $id ).'</div>';
            echo '<div class="portfolio-work">'. get_the_content().'</div>';
            echo '</div>';
          endwhile;
          endif;
        ?>
      </div><!-- #entry-content -->
      <?php comments_template( '', true ); ?>               
    <?php endwhile; // end of the loop. ?>                
  </div><!-- #content -->
</div><!-- #primary -->

<?php get_sidebar(); ?>
<?php get_footer(); ?>

4. Contributor Page With Avatar images

Next up in our page template use cases is a contributor page. We want to set up a list of authors on our website, including their images and the number of posts they have published under their name. The end result will look like this:

The completed custom contributors page.34
The completed custom contributors page. (View large version35)

We will again start out with our hybrid file from before and add the code for the contributor list to it. But what if you don’t know how to create such a thing? No worries, you can get by with intelligent stealing.

You see, the Twenty Fourteen default theme comes with a contributor page by default. You can find its template in the page-templates folder with the name contributors.php.

When looking into the file, however, you will only find the following call in there: twentyfourteen_list_authors();. Luckily, as an avid WordPress user you now conclude that this probably refers to a function in Twenty Fourteen’s function.php file and you would be right.

From what we find in there, the part that interests us is this:

<?php
// Output the authors list.
$contributor_ids = get_users( array(
  'fields'  => 'ID',
  'orderby' => 'post_count',
  'order'   => 'DESC',
  'who'     => 'authors',
));

foreach ( $contributor_ids as $contributor_id ) :
$post_count = count_user_posts( $contributor_id );
  // Move on if user has not published a post (yet).
  if ( ! $post_count ) 
    continue;
  
?>

<div class="contributor">
  <div class="contributor-info">
    <div class="contributor-avatar"><?php echo get_avatar( $contributor_id, 132 ); ?></div>
    <div class="contributor-summary">
      <h2 class="contributor-name"><?php echo get_the_author_meta( 'display_name', $contributor_id ); ?></h2>
      <p class="contributor-bio">
        <?php echo get_the_author_meta( 'description', $contributor_id ); ?>
      </p>
      <a class="button contributor-posts-link" href="<?php echo esc_url( get_author_posts_url( $contributor_id ) ); ?>">
        <?php printf( _n( '%d Article', '%d Articles', $post_count, 'twentyfourteen' ), $post_count ); ?>
      </a>
    </div><!-- .contributor-summary -->
  </div><!-- .contributor-info -->
</div><!-- .contributor -->

<?php
endforeach;
?>

We will again add it below the call for the_content() with the following result:

The unstyled custom contributors page.36
The unstyled custom contributors page. (View large version37)

Now for a little bit of styling:

/* Contributor page */

.contributor 
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing:      border-box;
  display: inline-block;
  padding: 48px 10px;

.contributor p 
  margin-bottom: 1rem;

.contributor-info 
  margin: 0 auto 0 168px;

.contributor-avatar 
  border: 1px solid rgba(0, 0, 0, 0.1);
  float: left;
  line-height: 0;
  margin: 0 30px 0 -168px;
  padding: 2px;

.contributor-avatar img
  border-radius: 0;

.contributor-summary 
  float: left;

.contributor-name
  font-weight: normal;
  margin: 0 !important;

.contributor-posts-link 
  background-color: #24890d;
  border: 0 none;
  border-radius: 0;
  color: #fff;
  display: inline-block;
  font-size: 12px;
  font-weight: 700;
  line-height: normal;
  padding: 10px 30px 11px;
  text-transform: uppercase;
  vertical-align: bottom;

.contributor-posts-link:hover 
  color: #000;
  text-decoration: none;

And that should be it. Thanks Twenty Fourteen!

5. Customized Archive Page

Twenty Twelve comes with its own template for archive pages. It will jump into action, for example, when you attempt to view all past posts from a certain category.

However, I want something a little more like what Problogger38 has done: a page that lets people discover additional content on my site in several different ways. That, again, is done with a page template.

Staying with our mixed template from before, we will add the following below the the_content() call:

<div class="archive-search-form"><?php get_search_form(); ?></div>

<h2>Archives by Year:</h2>
<ul><?php wp_get_archives('type=yearly'); ?></ul>

<h2>Archives by Month:</h2>
<ul><?php wp_get_archives('type=monthly'); ?></ul>
   
<h2>Archives by Subject:</h2>
<ul> <?php wp_list_categories('title_li='); ?></ul>

Plus, a little bit of styling for the search bar:

.archive-search-form 
  padding: 10px 0;
  text-align: center;

And the result should look a little bit like this:

The custom archive page.39
The custom archive page. (View large version40)

For completion’s sake, here is the entire file:

<?php
/**
 * Template Name: Custom archive template
 *
 */

get_header(); ?>

<div id="primary" class="site-content">
  <div id="content" role="main">

    <?php while ( have_posts() ) : the_post(); ?>
         
      <header class="entry-header">
        <?php the_post_thumbnail(); ?>
        <h1 class="entry-title"><?php the_title(); ?></h1>
      </header>

      <div class="entry-content">
        <?php the_content(); ?>
      
        <div class="archive-search-form"><?php get_search_form(); ?></div>

        <h2>Archives by Year:</h2>
        <ul><?php wp_get_archives('type=yearly'); ?></ul>

        <h2>Archives by Month:</h2>
        <ul><?php wp_get_archives('type=monthly'); ?></ul>
                
        <h2>Archives by Subject:</h2>
        <ul><?php wp_list_categories('title_li='); ?></ul>
      </div><!-- #entry-content -->

      <?php comments_template( '', true ); ?>               
    <?php endwhile; // end of the loop. ?>             
  </div><!-- #content -->
</div><!-- #primary -->

<?php get_sidebar(); ?>
<?php get_footer(); ?>

Don’t forget to assign it to a page!

WordPress Page Templates In A Nutshell

On your way to mastering WordPress, learning to use page templates is an important step. They can make customizing your website very, very easy and allow you to assign unique functionality and design to as many or few pages as you wish. From adding widget areas to showing custom post types to displaying a list of your website’s contributors — the possibilities are practically endless.

Whether you use conditional tags, exploit the WordPress template hierarchy, or create page-specific template files is entirely up to you and what you are trying to achieve. Start off small and work your way up to more complicated things. It won’t be long before every part of your WordPress website will answesr to your every call.

Do you have experience using page templates in WordPress? What other use cases can you add to the list? Any important details to add? Please tell us about it in the comments.

Image credit: Kevin Phillips41

(og, ml)

Footnotes

  1. 1 http://codex.wordpress.org
  2. 2 https://addons.mozilla.org/en-us/firefox/addon/firebug/
  3. 3 http://codex.wordpress.org/Template_Hierarchy#The_Template_Hierarchy_In_Detail
  4. 4 http://wphierarchy.com/
  5. 5 http://www.smashingmagazine.com/wp-content/uploads/2015/05/01-wp-template-hierarchy-opt.jpg
  6. 6 http://codex.wordpress.org/
  7. 7 http://www.smashingmagazine.com/wp-content/uploads/2015/05/01-wp-template-hierarchy-opt.jpg
  8. 8 http://codex.wordpress.org/Conditional_Tags
  9. 9 http://codex.wordpress.org/Conditional_Tags
  10. 10 http://www.themelab.com/ultimate-guide-wordpress-conditional-tags/
  11. 11 http://www.smashingmagazine.com/wp-content/uploads/2015/05/02-page-attributes-opt.jpg
  12. 12 http://www.smashingmagazine.com/wp-content/uploads/2015/05/02-page-attributes-opt.jpg
  13. 13 http://www.smashingmagazine.com/wp-content/uploads/2015/05/03-choose-page-template-manually-opt.jpg
  14. 14 http://www.smashingmagazine.com/wp-content/uploads/2015/05/03-choose-page-template-manually-opt.jpg
  15. 15 https://wordpress.org/plugins/what-the-file/
  16. 16 http://www.smashingmagazine.com/wp-content/uploads/2015/05/04-default-template-opt.jpg
  17. 17 http://www.smashingmagazine.com/wp-content/uploads/2015/05/04-default-template-opt.jpg
  18. 18 http://codex.wordpress.org/Page_Templates#Filenames
  19. 19 http://www.smashingmagazine.com/wp-content/uploads/2015/05/05-custom-wp-page-template-without-sidebar-opt.jpg
  20. 20 http://www.smashingmagazine.com/wp-content/uploads/2015/05/05-custom-wp-page-template-without-sidebar-opt.jpg
  21. 21 http://www.smashingmagazine.com/wp-content/uploads/2015/05/06-custom-full-width-wp-page-template-opt.jpg
  22. 22 http://www.smashingmagazine.com/wp-content/uploads/2015/05/06-custom-full-width-wp-page-template-opt.jpg
  23. 23 http://www.smashingmagazine.com/wp-content/uploads/2015/05/07-404-page-template-widgets-opt.jpg
  24. 24 http://www.smashingmagazine.com/wp-content/uploads/2015/05/07-404-page-template-widgets-opt.jpg
  25. 25 http://www.smashingmagazine.com/wp-content/uploads/2015/05/08-customized-404-error-page-via-template-opt.jpg
  26. 26 http://www.smashingmagazine.com/wp-content/uploads/2015/05/08-customized-404-error-page-via-template-opt.jpg
  27. 27 https://wordpress.org/plugins/types/
  28. 28 http://www.smashingmagazine.com/wp-content/uploads/2015/05/09-portfolio-page-without-custom-page-template-opt.jpg
  29. 29 http://www.smashingmagazine.com/wp-content/uploads/2015/05/09-portfolio-page-without-custom-page-template-opt.jpg
  30. 30 http://www.smashingmagazine.com/wp-content/uploads/2015/05/10-custom-portfolio-template-without-styling-opt.jpg
  31. 31 http://www.smashingmagazine.com/wp-content/uploads/2015/05/10-custom-portfolio-template-without-styling-opt.jpg
  32. 32 http://www.smashingmagazine.com/wp-content/uploads/2015/05/11-custom-portfolio-template-including-styling-opt.jpg
  33. 33 http://www.smashingmagazine.com/wp-content/uploads/2015/05/11-custom-portfolio-template-including-styling-opt.jpg
  34. 34 http://www.smashingmagazine.com/wp-content/uploads/2015/05/12-custom-contributor-page-opt.jpg
  35. 35 http://www.smashingmagazine.com/wp-content/uploads/2015/05/12-custom-contributor-page-opt.jpg
  36. 36 http://www.smashingmagazine.com/wp-content/uploads/2015/05/13-custom-contributor-page-without-styling-opt.jpg
  37. 37 http://www.smashingmagazine.com/wp-content/uploads/2015/05/13-custom-contributor-page-without-styling-opt.jpg
  38. 38 http://www.problogger.net/archives/
  39. 39 http://www.smashingmagazine.com/wp-content/uploads/2015/05/14-custom-archive-page-opt.jpg
  40. 40 http://www.smashingmagazine.com/wp-content/uploads/2015/05/14-custom-archive-page-opt.jpg
  41. 41 http://pixabay.com/en/users/kpgolfpro-27707/

The post A Detailed Guide To WordPress Custom Page Templates appeared first on Smashing Magazine.

Read article here:

A Detailed Guide To WordPress Custom Page Templates

How To Use Autoloading And A Plugin Container In WordPress Plugins

Building and maintaining1 a WordPress plugin can be a daunting task. The bigger the codebase, the harder it is to keep track of all the working parts and their relationship to one another. And you can add to that the limitations imposed by working in an antiquated version of PHP, 5.2.

In this article we will explore an alternative way of developing WordPress plugins, using the lessons learned from the greater PHP community, the world outside WordPress. We will walk through the steps of creating a plugin and investigate the use of autoloading and a plugin container.

Let’s Begin

The first thing you need to do when creating a plugin is to give it a unique name. The name is important as it will be the basis for all our unique identifiers (function prefix, class prefix, textdomain, option prefix, etc.). The name should also be unique across the wordpress.org space. It won’t hurt if we make the name catchy. For our sample plugin I chose the name Simplarity, a play on the words “simple” and “clarity”.

We’ll assume you have a working WordPress installation already.

Folder Structure

First, create a directory named simplarity inside wp-content/plugins. Inside it create the following structure:

  • simplarity.php: our main plugin file
  • css/: directory containing our styles
  • js/: directory containing JavaScript files
  • languages/: directory that will contain translation files
  • src/: directory containing our classes
  • views/: directory that will contain our plugin view files

The Main Plugin File

Open the main plugin file, simplarity.php, and add the plugin information header:

<?php
/*
Plugin Name: Simplarity
Description: A plugin for smashingmagazine.com
Version: 1.0.0
License: GPL-2.0+
*/

This information is enough for now. The plugin name, description, and version will show up in the plugins area of WordPress admin. The license details are important to let your users know that this is an open source plugin. A full list of header information can found in the WordPress codex2.

Autoloading

Autoloading allows you to automatically load classes using an autoloader so you don’t have to manually include the files containing the class definitions. For example, whenever you need to use a class, you need to do the following:

require_once '/path/to/classes/class-container.php';
require_once '/path/to/classes/class-view.php';
require_once '/path/to/classes/class-settings-page.php';

$plugin = new Container();
$view = new View();
$settings_page = new SettingsPage();

With autoloading, you can use an autoloader instead of multiple require_once3 statements. It also eliminates the need to update these require statements whenever you add, rename, or change the location of your classes. That’s a big plus for maintainability.

Adopting The PEAR Naming Convention For Class Names

Before we create our autoloader we need to create a convention for our class names and their location in the file system. This will aid the autoloader in mapping out the class to its source file.

For our class names we will adopt the PEAR naming convention4. The gist is that class names are alphabetic characters in StudlyCaps. Each level of the hierarchy is separated with a single underscore. Class names will directly map to the directories in which they are stored.

It’s easier to illustrate it using examples:

  • A class named Simplarity_Plugin would be defined in the file src/Simplarity/Plugin.php.
  • A class named Simplarity_SettingsPage would be defined in src/Simplarity/SettingsPage.php.

As you can see with this convention, the autoloader will just replace the underscores with directory separators to locate the class definition.

What About The WordPress Coding Standards For Class Names?

As you might be aware, WordPress has its own naming convention5 for class names. It states:

Class names should use capitalized words separated by underscores. Any acronyms should be all upper case. […] Class file names should be based on the class name with class- prepended and the underscores in the class name replaced with hyphens, for example WP_Error becomes class-wp-error.php

I know that we should follow the standards of the platform that we are developing on. However, we suggest using the PEAR naming convention because:

  • WP coding standards do not cover autoloading.
  • WP does not follow its own coding standards. Examples: class.wp-scripts.php and SimplePie. This is understandable since WordPress grew organically.
  • Interoperability allows you to easily use third-party libraries that follow the PEAR naming convention, like Twig. And conversely, you can easily port your code to other libraries sharing the same convention.
  • It’s important your autoloader is future-ready. When WordPress decides to up the ante and finally move to PHP 5.3 as its minimum requirement, you can easily update the code to be PSR-0 or PSR-4-compatible and take advantage of the built-in namespaces instead of using prefixes. This is a big plus for interoperability.

Note that we are only using this naming convention for classes. The rest of our code will still follow the WordPress coding standards. It’s important to follow and respect the standards of the platform that we are developing on.

Now that we have fully covered the naming convention, we can finally build our autoloader.

Building Our Autoloader

Open our main plugin file and add the following code below the plugin information header:

spl_autoload_register( 'simplarity_autoloader' );
function simplarity_autoloader( $class_name ) 
  if ( false !== strpos( $class_name, 'Simplarity' ) ) 
    $classes_dir = realpath( plugin_dir_path( __FILE__ ) ) . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR;
    $class_file = str_replace( '_', DIRECTORY_SEPARATOR, $class_name ) . '.php';
    require_once $classes_dir . $class_file;
  
}

At the heart of our autoloading mechanism is PHP’s built in spl_autoload_register6 function. All it does is register a function to be called automatically when your code references a class that hasn’t been loaded yet.

The first line tells spl_autoload_register to register our function named simplarity_autoloader:

spl_autoload_register( 'simplarity_autoloader' );

Next we define the simplarity_autoloader function:

function simplarity_autoloader( $class_name ) 
  …

Notice that it accepts a $class_name parameter. This parameter holds the class name. For example when you instantiate a class using $plugin = new Simplarity_Plugin(), $class_name will contain the string “Simplarity_Plugin”. Since we are adding this function in the global space, it’s important that we have it prefixed with simplarity_.

The next line checks if $classname contains the string “Simplarity” which is our top level namespace:

if ( false !== strpos( $class_name, 'Simplarity' ) ) 

This will ensure that the autoloader will only run on our classes. Without this check, our autoloader will run every time an unloaded class is referenced, even if the class is not ours, which is not ideal.

The next line constructs the path to the directory where our classes reside:

$classes_dir = realpath( plugin_dir_path( __FILE__ ) ) . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR;

It uses WP’s plugin_dir_path7 to get the plugin root directory. __FILE__ is a magic constant8 that contains the full path and filename of the current file. DIRECTORY_SEPARATOR is a predefined constant that contains either a forward slash or backslash depending on the OS your web server is on. We also use realpath9 to normalize the file path.

This line resolves the path to the class definition file:

$class_file = str_replace( '_', DIRECTORY_SEPARATOR, $class_name ) . '.php';

It replaces the underscore (_) in $class_name with the directory separator and appends .php.

Finally, this line builds the file path to the definition and includes the file using require_once:

require_once $classes_dir . $class_file;

That’s it! You now have an autoloader. Say goodbye to long lines of require_once statements.

Plugin Container

A plugin container is a special class that holds together our plugin code. It simplifies the interaction between the many working parts of your code by providing a centralized location to manage the configuration and objects.

Uses Of Our Plugin Container

Here are the things we can expect from the plugin container:

  • Store global parameters in a single location

    Often you’ll find this code in plugins:

    define( 'SIMPLARITY_VERSION', '1.0.0' );
    define( 'SIMPLARITY_PATH', realpath( plugin_dir_path( __FILE__ ) ) . DIRECTORY_SEPARATOR );
    define( 'SIMPLARITY_URL', plugin_dir_url( __FILE__ ) );
    

    Instead of doing that, we could do this instead:

    $plugin = new Simplarity_Plugin();
    $plugin['version] = '1.0.0';
    $plugin['path'] = realpath( plugin_dir_path( __FILE__ ) ) . DIRECTORY_SEPARATOR;
    $plugin['url'] = plugin_dir_url( __FILE__ );
    

    This has the added benefit of not polluting the global namespace with our plugin’s constants, which in most cases aren’t needed by other plugins.

  • Store objects in a single location

    Instead of scattering our class instantiations everywhere in our codebase we can just do this in a single location:

    $plugin = new Simplarity_Plugin();
    /…/
    $plugin['scripts'] = new Simplarity_Scripts(); // A class that loads javascript files
    
  • Service definitions

    This is the most powerful feature of the container. A service is an object that does something as part of a larger system. Services are defined by functions that return an instance of an object. Almost any global object can be a service.

    $plugin['settings_page'] = function ( $plugin ) 
      return new SettingsPage( $plugin['settings_page_properties'] );
    ;
    

    Services result in lazy initialization whereby objects are only instantiated and initialized when needed.

    It also allows us to easily implement a self-resolving dependency injection design. An example:

    $plugin = new Plugin();
    $plugin['door_width'] = 100;
    $plugin['door_height'] = 500;
    $plugin['door_size'] = function ( $plugin ) 
      return new DoorSize( $plugin['door_width'], $plugin['door_height'] );
    ;
    $plugin['door'] = function ( $plugin ) 
      return new Door( $plugin['door_size'] );
    ;
    $plugin['window'] = function ( $plugin ) 
      return new Window();
    ;
    $plugin['house'] = function ( $plugin ) 
      return new House( $plugin['door'], $plugin['window'] );
    ;
    $house = $plugin['house'];

    This is roughly equivalent to:

    $door_width = 100;
    $door_height = 500;
    $door_size = new DoorSize( $door_width, $door_height );
    $door = new Door( $door_size );
    $window = new Window();
    $house = new House( $door, $window );

    Whenever we get an object, as in $house = $plugin['house']; , the object is created (lazy initialization) and dependencies are resolved automatically.

Building The Plugin Container

Let’s start by creating the plugin container class. We will name it “Simplarity_Plugin”. As our naming convention dictates, we should create a corresponding file: src/Simplarity/Plugin.php.

Open Plugin.php and add the following code:

<?php
class Simplarity_Plugin implements ArrayAccess 
  protected $contents;
    
  public function __construct() 
    $this->contents = array();
  
  
  public function offsetSet( $offset, $value ) 
    $this->contents[$offset] = $value;
  

  public function offsetExists($offset) 
    return isset( $this->contents[$offset] );
  

  public function offsetUnset($offset) 
    unset( $this->contents[$offset] );
  

  public function offsetGet($offset) 
    if( is_callable($this->contents[$offset]) )
      return call_user_func( $this->contents[$offset], $this );
    
    return isset( $this->contents[$offset] ) ? $this->contents[$offset] : null;
  }
  
  public function run() 
    foreach( $this->contents as $key => $content ) // Loop on contents
      if( is_callable($content) )
        $content = $this[$key];
      
      if( is_object( $content ) )
        $reflection = new ReflectionClass( $content );
        if( $reflection->hasMethod( 'run' ) )
          $content->run(); // Call run method on object
        
      }
    }
  }
}

The class implements the ArrayAccess interface:

class Simplarity_Plugin implements ArrayAccess 

This allows us to use it like PHP’s array:

$plugin = new Simplarity_Plugin();
$plugin['version'] = '1.0.0'; // Simplicity is beauty

The functions offsetSet, offsetExists, offsetUnset and offsetGet are required by ArrayAccess to be implemented. The run function will loop through the contents of the container and run the runnable objects.

To better illustrate our plugin container, let’s start by building a sample plugin.

Example Plugin: A Settings Page

This plugin will add a settings page named “Simplarity” under WordPress Admin → Settings.

Let’s go back to the main plugin file. Open up simplarity.php and add the following code. Add this below the autoloader code:

add_action( 'plugins_loaded', 'simplarity_init' ); // Hook initialization function
function simplarity_init() 
  $plugin = new Simplarity_Plugin(); // Create container
  $plugin['path'] = realpath( plugin_dir_path( __FILE__ ) ) . DIRECTORY_SEPARATOR;
  $plugin['url'] = plugin_dir_url( __FILE__ );
  $plugin['version'] = '1.0.0';
  $plugin['settings_page_properties'] = array( 
    'parent_slug' => 'options-general.php',
    'page_title' =>  'Simplarity',
    'menu_title' =>  'Simplarity',
    'capability' => 'manage_options',
    'menu_slug' => 'simplarity-settings',
    'option_group' => 'simplarity_option_group',
    'option_name' => 'simplarity_option_name'
  );
  $plugin['settings_page'] = new Simplarity_SettingsPage( $plugin['settings_page_properties'] );
  $plugin->run();

Here we use WP’s add_action to hook our function simplarity_init into plugins_loaded:

add_action( 'plugins_loaded', 'simplarity_init' );

This is important as this will make our plugin overridable by using remove_action. An example use case would be a premium plugin overriding the free version.

Function simplarity_init contains our plugin’s initialization code. At the start, we simply instantiate our plugin container:

$plugin = new Simplarity_Plugin();

These lines assign global configuration data:

$plugin['path'] = realpath( plugin_dir_path( __FILE__ ) ) . DIRECTORY_SEPARATOR;
$plugin['url'] = plugin_dir_url( __FILE__ );
$plugin['version'] = '1.0.0';

The plugin path contains the full path to our plugin, the url contains the URL to our plugin directory. They will come in handy whenever we need to include files and assets. version contains the current version of the plugin that should match the one in the header info. Useful whenever you need to use the version in code.

This next code assigns various configuration data to settings_page_properties:

$plugin['settings_page_properties'] = array(
  'parent_slug' => 'options-general.php',
  'page_title' =>  'Simplarity',
  'menu_title' =>  'Simplarity',
  'capability' => 'manage_options',
  'menu_slug' => 'simplarity-settings',
  'option_group' => 'simplarity_option_group',
  'option_name' => 'simplarity_option_name'
);

These configuration data are related to WP settings API10.

This next code instantiates the settings page, passing along settings_page_properties:

$plugin['settings_page'] = new Simplarity_SettingsPage( $plugin['settings_page_properties'] );

The run method is where the fun starts:

$plugin->run();

It will call Simplarity_SettingsPage‘s own run method.

The Simplarity_SettingsPage Class

Now we need to create the Simplarity_SettingsPage class. It’s a class that groups together the settings API functions.

Create a file named SettingsPage.php in src/Simplarity/. Open it and add the following code:

<?php
class Simplarity_SettingsPage 
  protected $settings_page_properties;

  public function __construct( $settings_page_properties )
    $this->settings_page_properties = $settings_page_properties;
  

  public function run() 
    add_action( 'admin_menu', array( $this, 'add_menu_and_page' ) );
    add_action( 'admin_init', array( $this, 'register_settings' ) );
  

  public function add_menu_and_page()  

    add_submenu_page(
      $this->settings_page_properties['parent_slug'],
      $this->settings_page_properties['page_title'],
      $this->settings_page_properties['menu_title'], 
      $this->settings_page_properties['capability'],
      $this->settings_page_properties['menu_slug'],
      array( $this, 'render_settings_page' )
    );
  
    
  public function register_settings()  
    
    register_setting(
      $this->settings_page_properties['option_group'],
      $this->settings_page_properties['option_name']
    );   
  
   
  public function get_settings_data()
    return get_option( $this->settings_page_properties['option_name'], $this->get_default_settings_data() );
  
    
  public function render_settings_page() 
    $option_name = $this->settings_page_properties['option_name'];
    $option_group = $this->settings_page_properties['option_group'];
    $settings_data = $this->get_settings_data();
    ?>
    <div class="wrap">
      <h2>Simplarity</h2>
      <p>This plugin is using the settings API.</p>
      <form method="post" action="options.php">
        <?php
        settings_fields( $this->plugin['settings_page_properties']['option_group']);
        ?>
        <table class="form-table">
          <tr>
              <th><label for="textbox">Textbox:</label></th>
              <td>
                <input type="text" id="textbox"
                  name="<?php echo esc_attr( $option_name."[textbox]" ); ?>"
                  value="<?php echo esc_attr( $settings_data['textbox'] ); ?>" />
              </td>
          </tr>
        </table>
        <input type="submit" name="submit" id="submit" class="button button-primary" value="Save Options">
      </form>
    </div>
    <?php
  
   
  public function get_default_settings_data() 
    $defaults = array();
    $defaults['textbox'] = '';
      
    return $defaults;
  
}

The class property $settings_page_properties stores the settings related to WP settings API:

<?php
class Simplarity_SettingsPage 
  protected $settings_page_properties;

The constructor function accepts the settings_page_properties and stores it:

public function __construct( $settings_page_properties )
  $this->settings_page_properties = $settings_page_properties;

The values are passed from this line in the main plugin file:

$plugin['settings_page'] = new Simplarity_SettingsPage( $plugin['settings_page_properties'] );

The run function is use to run startup code:

public function run() 
  add_action( 'admin_menu', array( $this, 'add_menu_and_page' ) );
  add_action( 'admin_init', array( $this, 'register_settings' ) );

The most likely candidate for startup code are filters11 and action hooks12. Here we add the action hooks related to our settings page.
Do not confuse this run method with the run method of the plugin container. This run method belongs to the settings page class.

This line hooks the add_menu_and_page function on to the admin_menu action:

add_action( 'admin_menu', array( $this, 'add_menu_and_page' ) );

Function add_submenu_page in turn calls WP’s add_submenu_page13 function to add a link under the WP Admin → Settings:

public function add_menu_and_page()  

  add_submenu_page(
    $this->settings_page_properties['parent_slug'],
    $this->settings_page_properties['page_title'],
    $this->settings_page_properties['menu_title'], 
    $this->settings_page_properties['capability'],
    $this->settings_page_properties['menu_slug'],
    array( $this, 'render_settings_page' )
  );


As you can see, we are pulling the info from our class property $settings_page_properties which we specified in the main plugin file.

The parameters for add_submenu_page are:

  • parent_slug: slug name for the parent menu
  • page_title: text to be displayed in the <title> element of the page when the menu is selected
  • menu_title: text to be used for the menu
  • capability: the capability required for this menu to be displayed to the user
  • menu_slug: slug name to refer to this menu by (should be unique for this menu)
  • function: function to be called to output the content for this page

This line hooks the register_settings function on to the admin_init action:

add_action( 'admin_init', array( $this, 'register_settings' ) );

array( $this, 'register_settings' ) means to call register_settings on $this, which points to our SettingsPage instance.

The register_settings then calls WP’s register_setting to register a setting:

public function register_settings()  

  register_setting(
    $this->settings_page_properties['option_group'],
    $this->settings_page_properties['option_name']
  );

Function render_settings_page is responsible for rendering the page:

public function render_settings_page() 
  $option_name = $this->settings_page_properties['option_name'];
  $option_group = $this->settings_page_properties['option_group'];
  $settings_data = $this->get_settings_data();
  ?>
  <div class="wrap">
    <h2>Simplarity</h2>
    <p>This plugin is using the settings API.</p>
    <form method="post" action="options.php">
      <?php
      settings_fields( $option_group );
      ?>
      <table class="form-table">
        <tr>
          <th><label for="textbox">Textbox:</label></th>
          <td>
            <input type="text" id="textbox"
              name="<?php echo esc_attr( $option_name."[textbox]" ); ?>"
              value="<?php echo esc_attr( $settings_data['textbox'] ); ?>" />
          </td>
        </tr>
      </table>
      <input type="submit" name="submit" id="submit" class="button button-primary" value="Save Options">
    </form>
  </div>
  <?php

We hooked render_settings_page earlier using add_submenu_page.

Function get_settings_data is a wrapper function for get_option:

public function get_settings_data()
    return get_option( $this->plugin['settings_page_properties']['option_name'] );

This is to easily get the settings data with a single function call.

Function get_default_settings_data is use to supply us with our own default values:

public function get_default_settings_data() 
  $defaults = array();
  $defaults['textbox'] = '';
  
  return $defaults;

Abstracting Our Settings Page Class

Right now our settings page class cannot be reused if you want to create another subpage. Let’s move the reusable code for the settings page to another class.

Let’s call this class Simplarity_WpSubPage. Go ahead and create the file src/Simplarity/WpSubPage.php.

Now add the code below:

<?php
abstract class Simplarity_WpSubPage 
  protected $settings_page_properties;
   
  public function __construct( $settings_page_properties )
    $this->settings_page_properties = $settings_page_properties;
  
   
  public function run() 
    add_action( 'admin_menu', array( $this, 'add_menu_and_page' ) );
    add_action( 'admin_init', array( $this, 'register_settings' ) );
  
    
  public function add_menu_and_page()  

    add_submenu_page(
      $this->settings_page_properties['parent_slug'],
      $this->settings_page_properties['page_title'],
      $this->settings_page_properties['menu_title'],
      $this->settings_page_properties['capability'],
      $this->settings_page_properties['menu_slug'],
        array( $this, 'render_settings_page' )
    );
    
  
    
  public function register_settings()  
  
    register_setting(
      $this->settings_page_properties['option_group'],
      $this->settings_page_properties['option_name']
    );
  
  
   
  public function get_settings_data()
    return get_option( $this->settings_page_properties['option_name'], $this->get_default_settings_data() );
  
   
  public function render_settings_page()
      
  
   
  public function get_default_settings_data() 
    $defaults = array();
      
    return $defaults;
  
}

Notice that it is an abstract class. This will prevent intantiating this class directly. To use it you need to extend it first with another class, which in our case is Simplarity_SettingsPage:

<?php
class Simplarity_SettingsPage extends Simplarity_WpSubPage 
    
  public function render_settings_page() 
    $option_name = $this->settings_page_properties['option_name'];
    $option_group = $this->settings_page_properties['option_group'];
    $settings_data = $this->get_settings_data();
    ?>
    <div class="wrap">
      <h2>Simplarity</h2>
      <p>This plugin is using the settings API.</p>
      <form method="post" action="options.php">
        <?php
        settings_fields( $option_group );
        ?>
        <table class="form-table">
          <tr>
              <th><label for="textbox">Textbox:</label></th>
              <td>
                  <input type="text" id="textbox"
                      name="<?php echo esc_attr( $option_name."[textbox]" ); ?>"
                      value="<?php echo esc_attr( $settings_data['textbox'] ); ?>" />
              </td>
          </tr>
        </table>
        <input type="submit" name="submit" id="submit" class="button button-primary" value="Save Options">
      </form>
    </div>
    <?php
  
   
  public function get_default_settings_data() 
    $defaults = array();
    defaults['textbox'] = '';
      
    return $defaults;
  
}

The only functions we have implemented are render_settings_page and get_default_settings_data, which are customized to this settings page.

To create another WP settings page you’ll just need to create a class and extend the Simplarity_WpSubPage. And implement your own render_settings_page and get_default_settings_data.

Defining A Service

The power of the plugin container is in defining services. A service is a function that contains instantiation and initialization code that will return an object. Whenever we pull a service from our container, the service function is called and will create the object for you. The object is only created when needed. This is called lazy initialization.

To better illustrate this, let’s define a service for our settings page.

Open simplarity.php and add this function below the Simplarity code:

function simplarity_service_settings( $plugin )
   
  $object = new Simplarity_SettingsPage( $plugin['settings_page_properties'] );
  return $object;

Notice that our service function has a $plugin parameter which contains our plugin container. This allows us to access all configuration, objects, and services that have been stored in our plugin container. We can see that the Simplarity_SettingsPage has a dependency on $plugin['settings_page_properties']. We inject this dependency to Simplarity_SettingsPage here. This is an example of dependency injection. Dependency injection is a practice where objects are designed in a manner where they receive instances of the objects from other pieces of code, instead of constructing them internally. This improves decoupling of code.

Now let’s replace this line in simplarity_init:

$plugin['settings_page'] = new Simplarity_SettingsPage( $plugin['settings_page_properties'] );

with a service definition assignment:

$plugin['settings_page'] = 'simplarity_service_settings'

So instead of assigning our object instance directly, we assign the name of our function as string. Our container handles the rest.

Defining A Shared Service

Right now, every time we get $plugin['settings_page'], a new instance of Simplarity_SettingsPage is returned. Ideally, Simplarity_SettingsPage should only be instantiated once as we are using WP hooks, which in turn should only be registered once.

To solve this we use a shared service. A shared service will return a new instance of an object on first call, on succeeding calls it will return the same instance.

Let’s create a shared service using a static variable:

function simplarity_service_settings( $plugin )
  static $object;

  if (null !== $object) 
    return $object;
  
    
  $object = new Simplarity_SettingsPage( $plugin['settings_page_properties'] );
  return $object;
}

On first call, $object is null, and on succeeding calls it will contain the instance of the object created on first call. Notice that we are using a static variable. A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope.

That’s it.

Now if you activate the plugin, an admin menu will appear in Admin → Settings named “Simplarity”. Click on it and you will be taken to the settings page we have created.

Settings Page In Action14
Settings Page In Action

The Future: PHP 5.3+

Earlier we mentioned that our class naming convention was future-ready. In this section we will discuss how our codebase will work in PHP version 5.3 and up. Two of the best features that have graced the PHP world are namespaces and anonymous functions.

Namespaces

PHP does not allow two classes or functions to share the same name. When this happens, a name collision occurs and causes a nasty error.

With namespaces you can have the same class names as long as they live in their own namespace. A good analogy for namespaces are the folders you have in your OS. You cannot have files with the same name in one folder. However, you can have the same filenames in different folders.

With namespaces, class and function names won’t need unique prefixes anymore.

Anonymous Functions

Anonymous functions, also known as closures, allow the creation of functions which have no specified name. They are most useful as the value of callback parameters, but they have many other uses. You can also store closures in variables.

Here’s an example of closure:

<?php
$greet = function($name) 
  printf("Hello %srn", $name);
;

$greet('World');
$greet('PHP');

Using Namespaces In Classes

Let’s go ahead and use namespaces in our class definitions. Open up the following files in src/Simplarity:

  • Plugin.php
  • SettingsPage.php
  • WpSubPage.php

In each of these files, add a namespace declaration on top and remove the “Simplarity_” prefix on class names:

// Plugin.php
namespace Simplarity;

class Plugin 
...

// SettingsPage.php
namespace Simplarity;

class SettingsPage extends WpSubPage 
...

// WpSubPage.php
namespace Simplarity;

abstract class WpSubPage 
...

Since we have updated our class names we also need to update our class instantiations in simplarity.php. We do this by deleting the prefixes:

function simplarity_init() 
  $plugin = new Plugin();
  ...

...
function simplarity_service_settings( $plugin )

  ...
    
  $object = new SettingsPage( $plugin['settings_page_properties'] );
  return $object;

By default, PHP will try to load the class from the root namespace so we need to tell it about our namespaced classes. We add this to the top of simplarity.php just above the autoloader code:

use SimplarityPlugin;
use SimplaritySettingsPage;

This is called importing/aliasing with the use operator15.

Updating The Autoloader

Open up simplarity.php and change this line in the autoloader from:

$class_file = str_replace( '_', DIRECTORY_SEPARATOR, $class_name ) . '.php';

to:

$class_file = str_replace( '\', DIRECTORY_SEPARATOR, $class_name ) . '.php';

Remember that in 5.2 code we are using underscores as hierarchy separators. For 5.3+ we are using namespaces which use backslash “” as hierarchy separators. Thus we simply swap “_” for “”. We use another backslash to escape the original one: “\”.

Updating Our Service Definitions To Use Anonymous Functions

We can now replace the global functions we created for our service definitions with anonymous functions. So instead of doing this:

function simplarity_init() 
  ...
  $plugin['settings_page'] = 'simplarity_service_settings';
  ...

...
function simplarity_service_settings( $plugin )
  static $object;

  if (null !== $object) 
    return $object;
  
   
  $object = new Simplarity_SettingsPage( $plugin['settings_page_properties'] );
  return $object;
}

we can just replace this with an inline anonymous function:

function simplarity_init() 
  $plugin = new Plugin();
  ...
  $plugin['settings_page'] = function ( $plugin ) 
    static $object;
  
    if (null !== $object) 
      return $object;
    
    return new SettingsPage( $plugin['settings_page_properties'] );
  };
  ...
}

Using Pimple As A Plugin Container

Pimple is a small dependency injection (DI) container for PHP 5.3+. Pimple has the same syntax as our simple plugin container. In fact our plugin container was inspired by Pimple. In this part, we will extend Pimple and use it.

Download Pimple container from GitHub16 and save it in src/Simplarity/Pimple.php.

Open up Pimple.php and replace the namespace and the classname to:

...
namespace Simplarity;

/**
 * Container main class.
 *
 * @author  Fabien Potencier
 */
class Pimple implements ArrayAccess
...

Open up Plugin.php and replace all the code with:

<?php
namespace Simplarity;

class Plugin extends Pimple 
    
  public function run() 
    foreach( $this->values as $key => $content ) // Loop on contents
      $content = $this[$key];
      
      if( is_object( $content ) )
        $reflection = new ReflectionClass( $content );
        if( $reflection->hasMethod( 'run' ) )
            $content->run(); // Call run method on object
        
      }
    }
  }
}

Now let’s change the service definition in simplarity.php to:

$plugin['settings_page'] = function ( $plugin ) 
  return new SettingsPage( $plugin['settings_page_properties'] );
;

By default, each time you get a service, Pimple returns the same instance of it. If you want a different instance to be returned for all calls, wrap your anonymous function with the factory() method:

$plugin['image_resizer'] = $plugin->factory(function ( $plugin ) 
  return new ImageResizer( $plugin['image_dir'] );
);

Conclusion

The PHP community is big. A lot of best practices have been learned over the years. It’s good to always look beyond the walled garden of WordPress to look for answers. With autoloading and a plugin container we are one step closer to better code.

Code Samples

Resources

(dp, og, il)

Footnotes

  1. 1 https://shop.smashingmagazine.com/products/wordpress-maintenance-keeping-your-website-safe-and-efficient
  2. 2 http://codex.wordpress.org/Writing_a_Plugin
  3. 3 http://php.net/manual/en/function.require-once.php
  4. 4 http://pear.php.net/manual/en/standards.naming.php
  5. 5 https://make.wordpress.org/core/handbook/coding-standards/php/#naming-conventions
  6. 6 http://php.net/manual/en/function.spl-autoload-register.php
  7. 7 http://codex.wordpress.org/Function_Reference/plugin_dir_path
  8. 8 http://php.net/manual/en/language.constants.predefined.php
  9. 9 http://php.net/manual/en/function.realpath.php
  10. 10 http://codex.wordpress.org/Settings_API
  11. 11 http://codex.wordpress.org/Plugin_API/Filter_Reference
  12. 12 http://codex.wordpress.org/Plugin_API/Hooks
  13. 13 http://codex.wordpress.org/add_submenu_page
  14. 14 http://www.kosinix.com/wp-content/uploads/2015/02/simplarity1.png
  15. 15 http://php.net/manual/en/language.namespaces.importing.php
  16. 16 https://raw.githubusercontent.com/silexphp/Pimple/master/src/Pimple/Container.php
  17. 17 https://github.com/kosinix/simplarity
  18. 18 https://github.com/kosinix/simplarity-php53
  19. 19 http://pear.php.net/manual/en/standards.naming.php
  20. 20 http://daylerees.com/php-namespaces-explained
  21. 21 https://github.com/silexphp/Pimple

The post How To Use Autoloading And A Plugin Container In WordPress Plugins appeared first on Smashing Magazine.

Credit: 

How To Use Autoloading And A Plugin Container In WordPress Plugins