Advertisement
  1. Code
  2. Coding Fundamentals
  3. Game Development

Using Backbone Within the WordPress Admin: The Back End

Scroll to top
Read Time: 13 min

The rumours are true! The WordPress Admin Panel is now using Underscore and Backbone! This means that with minimal effort, we can begin to utilise these fantastic JavaScript libraries in our own plugins. This tutorial will show you exactly how you can do that. We'll create the Admin part of a Quiz plugin. We'll use a simple Custom Post Type to save Questions, and then within each question we'll add a meta box that will allow us to enter up to 4 answers and select which is the correct one. We'll be going through how to use templates, how to hook into click and key-up events, how to save data back to the WordPress database and most importantly, how to 'get your truth out of the Dom', as the creator Jeremy Ashkenas likes to put it.

I will say up front, that the plugin we are building in this tutorial may seem overly verbose for what it accomplishes. It will however, give you an excellent peek into the world of using Backbone and should you come across a project in the future that requires a complex user interface with a lot of JavaScript, you will be well armed and ready to bring much needed organisation to the party.


What We'll Do

In this first part, we'll set up the back end of our plugin. This will involve setting up the files and folders as well as implementing all of the features our plugin requires in PHP. We'll need to:

  1. Register a Custom Post Type - for our Questions
  2. Add a meta box that will allow us to enter answers on the same page
  3. Save information from the meta boxes when the post is saved
  4. Save information from our ajax requests (via Backbone)

Then in the Second Part...

Once we have our back end set up, we'll then proceed to output the required HTML for our meta box along with the data for each answer in JSON format. We'll also write the JavaScript that ties everything together. We'll cover:

  1. Outputting base HTML for the meta box
  2. Outputting a client-side template along with the answers in JSON
  3. The JavaScript needed to tie it all together

I hope this small series sounds interesting to you, and I'm looking forward to helping you get up and running with using Backbone.js within a WordPress plugin.


What We'll Build

This small plugin will use a Custom Post Type to save Questions. Then in a meta box, we'll create four inputs that will allow users to enter possible answers to the current question and select which of those is the correct answer. When an answer is changed, the corresponding save button will become active. When clicked, we'll use Backbone's built in model.save() method to save the data back to the WordPress database. Also, when the answers are being written in the inputs, the select box below it will automatically update its values as it will be looking out for changes to the models. All of these things are relatively trivial to do with Backbone and after reading this tutorial, you'll be able to start taking your plugins to the next level by using them within WordPress.

answers01

There's a lot to cover, so let's get started!


1. Create the Plugin

We need to do all the usual first steps involved with any plugin - create the files folders.

  1. Create a folder called wp_quiz
  2. Create a PHP file inside with the same name
  3. Create a folder called js
  4. Create a folder called src

Your folder structure should look like this.

files01

2. Add the Plugin Header

Inside of wp_quiz.php.

1
2
/*

3
Plugin Name: WP Quiz

4
Plugin URI: https://tutsplus.com/authors/Shane%20Osbourne

5
Description: An example of using Backbone within a plugin.

6
Author: Shane Osbourne

7
Version: 0.1

8
Author URI: https://tutsplus.com/authors/Shane%20Osbourne

9
*/

3. Add Hooks to Instantiate the Plugin

Still inside of wp_quiz.php, we need to do the following things:

  1. Include our main plugin class
  2. Create a function that will create an instance of the class
  3. Add a hook to only call the function when the user is an admin
1
2
/** wp_quiz.php **/
3
4
include 'src/WpQuiz.php'; // Class File

5
6
// Create an instance of the Plugin Class

7
function call_wp_quiz() {
8
	return new WpQuiz( 'admin' );
9
}
10
11
// Only when the current user is an Admin

12
if ( is_admin )
13
	add_action( 'init', 'call_wp_quiz' );
14
15
// Helper function

16
if ( ! function_exists( 'pp' ) ) {
17
	function pp() {
18
		return plugin_dir_url( __FILE__ );
19
	}
20
}

Putting the helper function pp() within this file will allow us to reference other files relative to the root of the plugin folder (you'll see that in action shortly).


4. Create the Plugin Class

Inside of the src folder, create a file called WpQuiz.php.

In this plugin class, we'll be needing a few different methods to accomplish all of the following:

  1. Register the Custom Post Type
  2. Add a meta box
  3. Retrieve the content for the meta box and output both HTML and some JSON data into it
  4. Listen for PUT requests and save data to the database
  5. Save our meta box data upon regular 'save' actions

Before we write the methods though, we're going to be storing some information as class properties. We store this information at the top of our class file so that modifications are easier to make later on. The answerIds array contains the keys that we'll be using throughout this plugin to save data using the built-in add_post_meta().

Add the Properties

1
2
/** src/WpQuiz.php  **/
3
class WpQuiz {
4
5
	// Names of Custom Post Type

6
	public $postTypeNameSingle = 'Question';
7
	public $postTypeNamePlural = 'Questions';
8
9
	// Meta Box Stuff

10
	public $metaBoxTitle = 'Answers';
11
	public $metaBoxTempl = 'templates/metabox.templ.php';
12
13
	// Question Id's

14
	public $answerIds = array( 'quiz-a-1', 'quiz-a-2', 'quiz-a-3', 'quiz-a-4' );
15
16
	// Javascript

17
	public $jsAdmin = '/js/admin.js';
18
19
}

Add the Constructor

  1. First we register the Custom Post Type using another helper method (which will be seen later on)
  2. Then we are registering a hook to load our meta box
  3. We also need a separate method for accepting our ajax requests
  4. Finally, when a page is loaded we'll want to save info from our meta box
1
2
/** src/WpQuiz.php  **/
3
4
public function __construct( $type ) {
5
	switch ( $type ) {
6
		case 'admin' :
7
			// Register the Post Type

8
			$this->registerPostType(
9
				$this->postTypeNameSingle,
10
				$this->postTypeNamePlural
11
			);
12
13
			// Add the Meta Box

14
			add_action( 'add_meta_boxes', array( $this, 'addMetaBox' ) );
15
16
			// Accept an Ajax Request

17
			add_action( 'wp_ajax_save_answer', array( $this, 'saveAnswers' ) );
18
19
			// Watch for Post being saved

20
			add_action( 'save_post', array( $this, 'savePost' ) );
21
	}
22
}

Add the Meta Box

  1. Add the JavaScript files needed for this plugin - again using a helper method (seen later)
  2. Create a unique ID for this plugin based on the name of the post type
  3. Add the meta box using the properties we set earlier
1
2
/** src/WpQuiz.php  **/
3
4
public function addMetaBox() {
5
6
	// Load the Javascript needed on this admin page.

7
	$this->addScripts();
8
9
	// Create an id based on Post-type name

10
	$id = $this->postTypeNameSingle . '_metabox';
11
12
	// Add the meta box

13
	add_meta_box(
14
		$id,
15
		$this->metaBoxTitle,
16
		array( $this, 'getMetaBox' ), // Get the markup needed

17
		$this->postTypeNameSingle
18
	);
19
20
}

Get the Meta Box Content

Here we are looping through our Answer IDs and constructing an array that contains post meta fetched with our helper method getOneAnswer. We make this new array so that we can encode it and send it to our template in JSON format - just the way Backbone likes it. We send data to our template using the $viewData array seen below. This keeps all of the HTML out of harm's way and allows us to work on it in a separate file. We'll take a quick look at the getTemplatePart method later on, but if you want an in-depth explanation about why I use it, please check out Improving Your Work-Flow – Separate Your Mark-Up From Your Logic!

1
2
/** src/WpQuiz.php  **/
3
4
public function getMetaBox( $post ) {
5
6
	// Get the current values for the questions

7
	$json = array();
8
	foreach ( $this->answerIds as $id ) {
9
		$json[] = $this->getOneAnswer( $post->ID, $id );
10
	}
11
12
	// Set data needed in the template

13
	$viewData = array(
14
		'post' => $post,
15
		'answers' => json_encode( $json ),
16
		'correct' => json_encode( get_post_meta( $post->ID, 'correct_answer' ) )
17
	);
18
19
	echo $this->getTemplatePart( $this->metaBoxTempl, $viewData );
20
21
}

Get a Single Answer - Helper

We are just returning an array of the data needed in our template. You can think of this as creating a single model that is needed on the front end.

1
2
/** src/WpQuiz.php  **/
3
4
public function getOneAnswer( $post_id, $answer_id ) {
5
	return array(
6
		'answer_id' => $answer_id,
7
		'answer' => get_post_meta( $post_id, $answer_id, true )
8
	);
9
}

Save Post

When a user clicks to save a post that our meta box is currently in, we need to do a couple of checks to ensure we are saving our Custom Post Type and that the current user has the correct permissions - if both checks are ok then we save the four answers from the meta box and the correct answer.

1
2
/** src/WpQuiz.php  **/
3
4
public function savePost( $post_id ) {
5
	// Check that we are saving our Custom Post type

6
	if ( $_POST['post_type'] !== strtolower( $this->postTypeNameSingle ) ) {
7
		return;
8
	}
9
10
	// Check that the user has correct permissions

11
	if ( ! $this->canSaveData( $post_id ) ) {
12
		return;
13
	}
14
15
	// Access the data from the $_POST global and create a new array containing

16
	// the info needed to make the save

17
	$fields = array();
18
	foreach ( $this->answerIds as $id ) {
19
		$fields[$id] = $_POST[$id];
20
	}
21
22
	// Loop through the new array and save/update each one

23
	foreach ( $fields as $id => $field ) {
24
		add_post_meta( $post_id, $id, $field, true );
25
		// or

26
		update_post_meta( $post_id, $id, $field );
27
	}
28
29
	// Save/update the correct answer

30
	add_post_meta( $post_id, 'correct_answer', $_POST['correct_answer'], true );
31
	// or

32
	update_post_meta( $post_id, 'correct_answer', $_POST['correct_answer'] );
33
34
}

Save Answers From Ajax Requests

This is where we will receive data passed to the server from Backbone. We need to:

  1. Access data sent as a PUT request. As it will be in JSON format, we need to decode it
  2. Again check that the current user has relevant permissions
  3. Go ahead and attempt the save
  4. If either Add or Update was successful, we can simply return the newly saved data and Backbone will view this as a successful save
  5. If neither were successful, we just return 0 to indicate a failure
1
2
/** src/WpQuiz.php  **/
3
4
public function saveAnswers() {
5
	// Get PUT data and decode it

6
	$model = json_decode( file_get_contents( "php://input" ) );
7
8
	// Ensure that this user has the correct permissions

9
	if ( ! $this->canSaveData( $model->post_id ) ) {
10
		return;
11
	}
12
13
	// Attempt an insert/update

14
	$update = add_post_meta( $model->post_id, $model->answer_id, $model->answer, true );
15
	// or

16
	$update = update_post_meta( $model->post_id, $model->answer_id, $model->answer );
17
18
	// If a save or update was successful, return the model in JSON format

19
	if ( $update ) {
20
		echo json_encode( $this->getOneAnswer( $model->post_id, $model->answer_id ) );
21
	} else {
22
		echo 0;
23
	}
24
	die();
25
}

The Helper Methods

Here are the four helpers mentioned in the above snippets.

  1. canSaveData() - This just ensures that the current user has the relevant permissions to edit / update this post.
  2. addScripts() - Note that here we are ensuring that we pass the 5th param to the wp_register_script() function. This will load our custom JavaScript into the footer and will ensure that our JSON data is available. Also, if you are using the WordPress editor in your plugin, you do not need to specify Backbone as a dependency as it will already be available to you. I'm including it here for the sake of the example though.
  3. registerPostType() - This is something I use often in plugins. It just makes life easier when adding a new Custom Post Type. It accepts both singular and plural versions of the name because it's not always as easy as just adding an 's'.
  4. getTemplatePart() - I've never been fond of having mark-up inside of my methods. This little helper will allow the use of a separate template file.
1
2
/** src/WpQuiz.php  **/
3
4
/**

5
* Determine if the current user has the relevant permissions

6
*

7
* @param $post_id

8
* @return bool

9
*/
10
private function canSaveData( $post_id ) {
11
	if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
12
		return false;
13
	if ( 'page' == $_POST['post_type'] ) {
14
		if ( ! current_user_can( 'edit_page', $post_id ) )
15
			return false;
16
	} else {
17
		if ( ! current_user_can( 'edit_post', $post_id ) )
18
			return false;
19
	}
20
	return true;
21
}
22
23
private function addScripts() {
24
	wp_register_script( 'wp_quiz_main_js', pp() . $this->jsAdmin , array( 'backbone' ), null, true );
25
	wp_enqueue_script( 'wp_quiz_main_js' );
26
}
27
28
/**

29
* Register a Custom Post Type

30
*

31
* @param $single

32
* @param $plural

33
* @param null $supports

34
*/
35
private function registerPostType( $single, $plural, $supports = null ) {
36
37
	$labels = array(
38
		'name' => _x( $plural, 'post type general name' ),
39
		'singular_name' => _x( "$single", 'post type singular name' ),
40
		'add_new' => _x( "Add New $single", "$single" ),
41
		'add_new_item' => __( "Add New $single" ),
42
		'edit_item' => __( "Edit $single" ),
43
		'new_item' => __( "New $single" ),
44
		'all_items' => __( "All $plural" ),
45
		'view_item' => __( "View $single" ),
46
		'search_items' => __( "Search $plural" ),
47
		'not_found' => __( "No $plural found" ),
48
		'not_found_in_trash' => __( "No $single found in Trash" ),
49
		'parent_item_colon' => '',
50
		'menu_name' => $plural
51
	);
52
	$args = array(
53
		'labels' => $labels,
54
		'public' => true,
55
		'publicly_queryable' => true,
56
		'show_ui' => true,
57
		'show_in_menu' => true,
58
		'query_var' => true,
59
		'rewrite' => true,
60
		'capability_type' => 'post',
61
		'has_archive' => true,
62
		'hierarchical' => false,
63
		'menu_position' => null,
64
		'supports' => ( $supports ) ? $supports : array( 'title', 'editor', 'page-attributes' )
65
	);
66
	register_post_type( $single, $args );
67
}
68
69
/**

70
* Render a Template File

71
*

72
* @param $filePath

73
* @param null $viewData

74
* @return string

75
*/
76
public function getTemplatePart( $filePath, $viewData = null ) {
77
78
	( $viewData ) ? extract( $viewData ) : null;
79
80
	ob_start();
81
	include ( "$filePath" );
82
	$template = ob_get_contents();
83
	ob_end_clean();
84
85
	return $template;
86
}

5. On to the Front End

At this point, we've set up everything needed for our back end. It's time to take a break and prepare for the next part where we'll be getting down and dirty with client-side templates, JavaScript and Backbone.js. I hope to see you there - it's going to be a good one.

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.