A simple guide to generate action elements in your custom meta boxes

Eventhough adding meta boxes to the WordPress post editing screen might have given you many sleepless nights, it’s not all that complicated as it seems to be. Serving as tremendously effective tools for extending the feature-set in your WordPress site, these meta boxes are elements you can’t afford to skip for sure.

custom meta boxes

What all you’ll find in this tutorial?

As you read through this tutorial, you’ll get a clearer picture about meta boxes, their significance and the method that’s utilized for generating them along with different action elements( for eg: textbox, radio-button, checkbox etc.).

Starting off with understanding Post Meta Boxes better

Well, a post meta box is basically a draggable box available within the WordPress admin area. It allows you(the website administrator) to select or include details in addition to the main content for a particular post/ page. For example, if you want to distinguish the posts based on genre or post id then the same can be easily achieved with the help of a custom meta box. To sum it up, you can incorporate custom functionality in your WordPress site, making it stand out from the crowd.

An example that evokes the need for custom meta boxes

Consider a situation where you’re developing a WordPress website that needs to showcase a detailed listing of bikes based on their individual model number. In addition to this, you are also being asked to create individual blog posts for every bike. Although, WordPress allows you to use categories and tags for distinguishing the bikes, what if you want to segregate them on the basis of model numbers? It is here that custom meta boxes serve handy.

And now, its time to know about the steps that would mark the generation of Custom Meta Boxes

Step 1Open your WordPress theme’s functions.php file and add the below mentioned code to it:

function wdm_add_meta_box() {
add_meta_box(‘wdm_sectionid’, ‘Make This Post Featured’, ‘wdm_meta_box_callback’, ‘post’);
}
add_action( ‘add_meta_boxes’, ‘wdm_add_meta_box’ );

Here’s an explanation of elements used in the above code:

  • add_meta_box: This is a function that utilizes specific parameters which inform WordPress about the addition of a new meta box.
  • wdm_sectionid: This represents the HTML ‘id’ attribute of the WP Post editing screen
  • ‘wdm_meta_box_callback, ‘post’)’: This line of code prints out the HTML for the new post edit screen. Here, post/page is used, depending on whether you are using the meta box on post screen or page screen
  • add_action( ‘add_meta_boxes’, ‘wdm_add_meta_box’): This is the WordPress action hook which instructs WordPress to add the new custom meta box.

Step 2- Generate the HTML Output

As the next step, you need to generate the HTML output which would also offer you an additional flexibility of using any HTML tags that suit your preferences. Code snippet for this is displayed below:

function wdm_meta_box_callback( $post ) {

wp_nonce_field( ‘wdm_meta_box’, ‘wdm_meta_box_nonce’ );

$value = get_post_meta( $post->ID, ‘featured’, true ); //my_key is a meta_key. Change it to   whatever you want
?>
<label for=”wdm_new_field”><?php _e( “Set As Featured:”, ‘set_as_featured’ ); ?></label>
<br />
<input type=”radio” name=”featured” value=”yes” <?php checked( $value, ‘yes’ ); ?> >Yes<br>
<input type=”radio” name=”featured” value=”no” <?php checked( $value, ‘no’ ); ?> >No
<?php
}

That’s it! With this step you’re done with creating custom meta boxes for your WordPress setup.

Now, let’s come to the method utilized for generating action elements for the custom meta box created above.

Every custom meta box needs to include some or the other action elements in the form of drop-down menus, textboxes, checkboxes, radio-buttons, multi select boxes etc. It is with the help of these action elements that you’ll be able to enjoy an enhanced control over all the information that is being displayed for your WordPress post/page.

Here’s a look at the different steps that are included within the process of injecting action elements(in this tutorial, I’ll be covering radio-button, drop down menu and textboxes only) into the custom metabox.

Before you proceed, please note all the code snippets mentioned below are related to the bikes example I covered in the very beginning of this tutorial.

Step 1- Create textbox, dropdown list and radio-buttons which need to be added to the custom meta box

  • Textbox creation for different parameters of bike
  1. Code used for generating textbox for bike model number:

<p>
<label>Model Number: </label>
<input type=”text” name=”bike_model_number”/>
</p>

  1. Code used for generating textbox for bike prices

<p>
<label>Price: </label>
<input type=”text” name=”bike_price”/>
</p>

  1. Code used for generating textbox for bike color

<p>
<label>Color: </label>
<input type=”text” name=”bike_color”/>
</p>

  • Dropdown list– Now that you’ve a textbox in place, its time to incorporate yet another popular action element i.e. drop down list to our meta box. Do note this dropdown list will be created on the basis of model year for bikes. Just use the below code snippet:

<p>
<label>Select Year: </label>
<select name =”model_year”>
<option value=”2001″>2001</option>
<option value=”2002″>2002</option>
<option value=”2003″>2003</option>
<option value=”2004″>2004</option>
<option value=”2005″>2005</option>
<option value=”2006″>2006</option>
<option value=”2007″>2007</option>
<option value=”2008″>2008</option>
<option value=”2009″>2009</option>
<option value=”2010″>2010</option>
<option value=”2011″>2011</option>
</select>
</p>

 

  • Radio-buttons- Choosing between mutually exclusive options has become easy with the emergence of radio-buttons. To put it simply, on selecting a single radio-button out of a group of four, the remaining three get deselected automatically. Here’s the code you need to use for adding radio-button to your custom meta box:

<p>
<label for=”wdm_new_field”><?php _e( “Set As Featured:”, ‘set_as_featured’ ); ?></label>
<input type=”radio” name=”featured” value=”yes” <?php checked( $value, ‘yes’ ); ?> >Yes
<input type=”radio” name=”featured” value=”no” <?php checked( $value, ‘no’ ); ?> >No
</p>
<div class=”clear”></div>
</div>
<?php
}
Step 2- Save the metabox with action elements created above

The code associated with this step is displayed below:

function wdm_save_meta_box_data( $post_id ) {

if ( !isset( $_POST[‘wdm_meta_box_nonce’] ) ) {
return;
}
if ( !wp_verify_nonce( $_POST[‘wdm_meta_box_nonce’], ‘wdm_meta_box’ ) ) {
return;
}
if ( defined( ‘DOING_AUTOSAVE’ ) && DOING_AUTOSAVE ) {
return;
}
if ( !current_user_can( ‘edit_post’, $post_id ) ) {
return;
}

If you carefully observe the above code snippet and all the others prior to this one, you’ll find the addition of multiple HTML Tags. Therefore, in order to ensure smooth performance of all the action elements, you need to add a code that can fetch individual values from each of these HTML tags. This brings us to the next step.

Step 3- Fetch values from different HTML tags

The code snippet applicable for the same is shown below:

//Code fetches value from the html tags.

$new_meta_value = ( isset( $_POST[‘featured’] ) ? sanitize_html_class( $_POST[‘featured’] ) : ” );
$model_number = ( isset( $_POST[‘model_year’] ) ? sanitize_html_class( $_POST[‘model_year’] ) : ” );
$price = ( isset( $_POST[‘car_price’] ) ? sanitize_html_class( $_POST[‘bike_price’] ) : ” );
$car_color = ( isset( $_POST[‘bike_color’] ) ? sanitize_html_class( $_POST[‘bike_color’] ) : ” );

Step 4- Add post meta data to WordPress database

Now that you’ve completed the procedure of creating action elements and fetching their values from HTML tags, it’s time to add the post meta data into your WP database. Here is the code associated with the same:

//Code to insert the post meta data in wordpress database

update_post_meta( $post_id, ‘featured’, $new_meta_value );
update_post_meta( $post_id, ‘model_year’, $model_number );
update_post_meta( $post_id, ‘bike_price’, $price );
update_post_meta( $post_id, ‘bike_color’, $bike_color );

}

A hard-to-miss add-on

Under situations where you intend to add a tint of style to your metabox, all you need to do is add a simple code. For this tutorial, the code that I’ll be adding is displayed below:

function wdm_admin_styles(){
global $typenow;
if( $typenow == ‘post’ ) {
wp_enqueue_style( ‘prfx_meta_box_styles’, get_template_directory_uri(). ‘/css/meta-box-styles.css’ );
}
}
add_action( ‘admin_print_styles’, ‘wdm_admin_styles’ );

The addition of above code will inject a meta-box-styles.css in your template directory where you can opt for adding your own unique style for achieving a better look and feel for the custom meta box created above.

Here’s the screen-shot for the newly created metabox(loaded with action elements):

kerry

 

In Conclusion

With appropriate addition of action elements, you can conveniently boost the functioning of your website’s custom metabox. Hope the above tutorial would’ve helped you dig deep into using custom meta boxes in the right way.

——————————————————-

Author Bio – Sarah Parker is a WordPress developer by profession, works for PSD to wordpress service company. Get in touch with her to maximize the profits by adding new features in the website.

Leave a Reply

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