Separating frontend and admin code


In most cases, your plugin has stuff it needs to do in the admin area. It probably also has stuff it needs to do in the frontend. These two never happen at the same time, so you can actually separate the two. The easiest way of separating frontend and backend code is having a set of classes, most of my plugins end up with at least three classes:

A common class, for stuff that is needed everywhere, for instance declaring a custom post type.
An admin class, for all the admin related stuff, like my admin settings page.
A frontend class, for all the stuff that is specific to the frontend, like loading a script or performing a shortcode.

You separate these by checking for two simple things:
1 if ( is_admin() )
2 require ‘class-admin.php’;
3 else
4 require ‘class-frontend.php’;

Easy enough right? Well you might want to take it even one step further. WordPress sets a constant for when you’re doing an AJAX request. This constant is DOING_AJAX. When WordPress is performing an AJAX request in the admin area, you probably won’t need to load the code for your admin settings pages, but you do need to load the code for your AJAX requests.

Separating.

So you’ll end up with code like this:
1 if ( is_admin() ) {
2 if ( defined(‘DOING_AJAX’) && DOING_AJAX )
3 require ‘class-admin-ajax.php’;
4 else
5 require ‘class-admin.php’;
6 } else {
7 require ‘class-frontend.php’;
8 }

This also means that the first snippet should be amended a bit, even when you’re not doing anything with AJAX, you should load it like this:
1 if ( is_admin() && ( !defined( ‘DOING_AJAX’ ) || !DOING_AJAX ) )
2 require ‘class-admin.php’;
3 else
4 require ‘class-frontend.php’;

By loading your code in a modular way like that, you’re making 100% sure your code has the lightest footprint possible and you’re not loading stuff that you (could) know upfront will never be used.

Advertisements

COMMENT PLEASE..!

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s