Using Ajax in WordPress Admin Meta Boxes

The introduction of custom post types in wordpress has cetainly created new markets for the software and brought it into the realm of CMS. For a recent project, we needed to create some pretty interesting meta boxes in the WordPress admin section for custom post types. We needed to create a new meta box that looked like the “Categories” meta box, but behaved differently. Instead of a category, we wanted to create a Slider meta box. The purpose of this slider meta box is to be able to add a new “slider” when creating slides and then link that slide to a specific slider. So when you click the “Add New Slider” link, instead of a parent category drop-down, we needed a slider type drop-down. The reason for this is two-fold: 1). the custom taxonomy slider is not hierarchical 2). each slider has a custom meta field slider_type that determines which types of slides can be added to any slider – nivo, cycle active, cycle content. The reason for this restriction is to make sure that only slides of the same “type” can be added to a slider of that type. It wouldn’t make sense to build a slider that have nivo and cycle active slides in it because it just wouldn’t work. Luckily for us, the wordpress admin is setup to catch ajax calls pretty easily using /wp-admin/admin-ajax.php. To accomplish our goal, we needed three things: 1). remove and clone the “Categories” meta box 2). create a php function to catch the ajax call and 3) write some jquery to make the ajax post.

1). Cloning the Meta Box

Really, the easiest step in the whole ordeal, was cloning the meta box.  If you read up on adding meta boxes, you’ll see that adding a new meta box is as easy as this:

function add_custom_categories_box() {
    add_meta_box('customcategorydiv', 'Sliders', 'custom_post_categories_meta_box', 'slides', 'side', 'low', array( 'taxonomy' => 'sliders' ));
}
add_action('admin_menu', 'add_custom_categories_box');

From that bit above, the thing we care about the most is custom_post_categories_meta_box. This is the function that will output the content of our new meta box. The form is nearly identical to the old, except we want to replace the code the creates a drop-down of available categories, with a drop-down that lists available slider types

  $taxonomy, 'hide_empty' => 0, 'name' => 'new'.$taxonomy.'_parent', 'orderby' => 'name', 'hierarchical' => 1, 'show_option_none' => '— ' . $tax->labels->parent_item . ' —', 'tab_index' => 3 ) )*/
 'Nivo Slider',
		'cycle_content'=>'Cycle Content Slider',
		'cycle_active'=>'Cycle Active Slider'
		);
 ?>

 

And that’s really all that we need to do to get a new Slider meta box on the slides page with a drop down that lists the slider type instead of the parent category. But, slider_type is a custom meta field and will not be saved to the new slider once you click the “Add New Slider” button. This is where the ajax comes in.

2). PHP Function to Catch Ajax Post

Originally, my thought was that I would try and alter the default wordpress jquery to pass my new custom meta slider_type. Then I realized this was going to be more work than necessary. Instead, I’d just write a quick php function to catch my ajax post and save it to the database. Here’s the code on how I accomplished that:

function ajaxResponse(){
    Try{
 	$new_term = wp_insert_term( $_POST['slider_name'], 'sliders', $args = array() );
	$t_id = $new_term['term_id'];
	$term_meta['slider_type'] = $_POST['type'];
        // Save the option array.
	$term = "taxonomy_".$t_id;
	update_option($term, $term_meta );
	echo $t_id;
 } catch (Exception $e){
	exit;
 }
 exit;
 }
add_action('wp_ajax_ak_attach', 'ajaxResponse');

The important thing to notice about that code is action – wp_ajax_ak_attach. You can call pretty much any hook in jQuery, provided that the name of the hook begins with wp_ajax_. Pretty cool, right. Otherwise, the php function itself is pretty self explanatory – grab $_POST variables (from jQuery), add a new slider, update the new slider using id with the slider_type info. Now we just need a bit of jQuery to make that happen.

3). Tying it together with jQuery

The jQuery is pretty simple as well. We’re listening for the click event of our “Add New Slider” button, and then we’re going to make a jQuery.post and call our php function:

jQuery(document).ready(function(){
	jQuery('input#sliders-add').click(function(){
		//jQuery(formid+"_contactForm button").hide();
		jQuery.post(
			site.siteurl+"/wp-admin/admin-ajax.php",
			//Data
			{
				action:"ak_attach",
				'cookie': encodeURIComponent(document.cookie),
				'slider_name':jQuery('input#newsliders').val(),
				'type':jQuery('#term_meta_slider_type').val()
			},
			//on success function
                       function(id){
                        /* Do Some Stuff in here to update elements on the page...*/
                       /*Reset the form*/
                       jQuery('input#newsliders').val('');
		       jQuery('#sliders-adder').addClass('wp-hidden-children');

	      	       return false;
			};
		);
	return false;
});

The jQuery code above is a pretty standard jQuery.post example. The important thing to notice in it is this part:

//Data
{
  action:"ak_attach",
  'cookie': encodeURIComponent(document.cookie),
  'slider_name':jQuery('input#newsliders').val(),
  'type':jQuery('#term_meta_slider_type').val()
}

The “action” is the name of our php function that we created, minus “wp_ajax_”, and our post variables are defined as well – “slider_name”, “type”. So now when someone presses the “Add New Slider” button, it’ll trigger an ajax post to our server-side function, which’ll pickup the post data that we’re defining and add the new slider and assign it the custom meta data slider_type Here’s some screenshots of it in action:

Adding New Slider

After Saving


This entry was posted in Development. Bookmark the permalink.

CommentsNo comments

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Contact Us

Wordpress Sliding Drawer Plugin

This jQuery powered sliding content area is made possible by 61 Designs Free Sliding Drawer Content Area Plugin. The plugin features an easy to use admin section where you can control everything from the position, color and text of the plugin. It also features up to 4 unique widget areas on the fly letting you drop anything into your sliding area with ease. The contact form below is a shortcode we dropped in a text widget.

Read more about the plugin in this blogpost…Read More

Contact Us





captcha