In this article, we’ll see How To Create Custom Post Meta Boxes In WordPress.
Table of Contents
When it comes to content creation in WordPress, thinking outside the box can lead to remarkable results.
While custom post meta boxes in WordPress offer fantastic opportunities for enhancing content management, why not explore unconventional methods to create them?
We’ll embark on a unique journey of creating custom post meta boxes in WordPress, where we’ll explore innovative approaches and tools that will elevate your content creation process.
Get ready to break free from traditional methods and unlock the full potential of custom post meta boxes in WordPress!
Custom Post Meta Boxes In WordPress
Creating custom post meta boxes in wordpress is extremely simple, at least it is once you’ve created your first one using the tools baked into WordPress’ core code.
We’ll walk you through everything you need to know about How To Create Custom Post Meta Boxes In WordPress:
- Creating custom post meta boxes in WordPress.
- Using custom post meta boxes in WordPress with any post type.
- Handling data validation.
- Saving custom meta data.
- Retrieving custom meta data on the front end.
What is a post meta box?
A post meta box is a draggable box shown on the post editing screen. Its purpose is to allow the user to select or enter information in addition to the main post content. This information should be related to the post in some way.
Generally, two types of data is entered into meta boxes:
Metadata (i.e. custom fields),
Taxonomy terms.
Of course, there are other possible uses, but those two are the most common. For the purposes of this tutorial, you’ll be learning how to develop meta boxes that handle custom post metadata.
What is post metadata?
Post metadata is data that’s saved in the wp_postmeta table in the database. Each entry is saved as four fields in this table:
meta_id: A unique ID for this specific metadata.
post_id: The post ID this metadata is attached to.
meta_key: A key used to identify the data (you’ll work with this often).
meta_value: The value of the metadata.
metadata is just key/value pairs saved for a specific post. This allows you to add all sorts of custom data to your posts. It is especially useful when you’re developing custom post types.
The only limit is your imagination.
Note: One thing to keep in mind is that a single meta key can have multiple meta values. This isn’t a common use, but it can be extremely powerful.
Working with post metadata
By now, you’re probably itching to build some custom meta boxes. However, to understand how custom meta boxes are useful, you must understand how to add, update, delete, and get post metadata.
I could write a book on the various ways to use metadata, but that’s not the main purpose of this tutorial. You can use the following links to learn how the post meta functions work in WordPress if you’re unfamiliar with them.
add_post_meta(): Adds post metadata.
update_post_meta(): Updates post metadata.
delete_post_meta(): Deletes post metadata.
get_post_meta(): Retrieves post metadata.
The remainder of this tutorial assumes that you’re at least familiar with how these functions work.
Building custom post meta boxes in WordPress
Now that you know what you’re building, it’s time to start diving into some code. The first two code snippets in this section of the tutorial are mostly about setting everything up for the meta box functionality.
Since you only want your post meta box to appear on the post editor screen in the admin, you’ll use the load-post.php and load-post-new.php hooks to initialize your meta box code.
/* Fire our meta box setup function on the post editor screen. */
add_action( 'load-post.php', 'smashing_post_meta_boxes_setup' );
add_action( 'load-post-new.php', 'smashing_post_meta_boxes_setup' );
Most WordPress developers should be familiar with how hooks work, so this should not be anything new to you.
The above code tells WordPress that you want to fire the smashing_post_meta_boxes_setup function on the post editor screen.
The next step is to create this function.
The following code snippet will add your meta box creation function to the add_meta_boxes hook. WordPress provides this hook to add meta boxes.
/* Meta box setup function. */
function smashing_post_meta_boxes_setup() {
/* Add meta boxes on the ‘add_meta_boxes’ hook. */
add_action( ‘add_meta_boxes’, ‘smashing_add_post_meta_boxes’ );
}
Now, you can get into the fun stuff.
In the above code snippet, you added the smashing_add_post_meta_boxes() function to the add_meta_boxes hook.
This function’s purpose should be to add custom post meta boxes in wordpress.
In the next example, you’ll create a single meta box using the add_meta_box() WordPress function. However, you can add as many meta boxes as you like at this point when developing your own projects.
Before proceeding, let’s look at the add_meta_box() function:
add_meta_box( $id, $title, $callback, $page, $context = 'advanced', $priority = 'default', $callback_args = null );
$id
: This is a unique ID assigned to your meta box. It should have a unique prefix and be valid HTML.$title
: The title of the meta box. Remember to internationalize this for translators.$callback
: The callback function that displays the output of your meta box.$page
: The admin page to display the meta box on. In our case, this would be the name of the post type (post
,page
, or a custom post type).$context
: Where on the page the meta box should be shown. The available options arenormal
,advanced
, andside
.$priority
: How high/low the meta box should be prioritized. The available options aredefault
,core
,high
, andlow
.$callback_args
: An array of custom arguments you can pass to your$callback
function as the second parameter.
The following code will add the post class meta box to the post editor screen.
/* Create one or more meta boxes to be displayed on the post editor screen. */
function smashing_add_post_meta_boxes() {
add_meta_box(
'smashing-post-class', // Unique ID
esc_html__( 'Post Class', 'example' ), // Title
'smashing_post_class_meta_box', // Callback function
'post', // Admin page (or post type)
'side', // Context
'default' // Priority
);
}
You still need to display the meta box’s HTML though. That’s where the smashing_post_class_meta_box() function comes in ($callback parameter from above).
/* Display the post meta box. */
function smashing_post_class_meta_box( $object, $box ) { ?>
<?php wp_nonce_field( basename( __FILE__ ), 'smashing_post_class_nonce' ); ?>
<p>
<label for="smashing-post-class"><?php _e( "Add a custom CSS class, which will be applied to WordPress' post class.", 'example' ); ?></label>
<br />
<input class="widefat" type="text" name="smashing-post-class" id="smashing-post-class" value="<?php echo esc_attr( get_post_meta( $object->ID, 'smashing_post_class', true ) ); ?>" size="30" />
</p>
<?php }
Saving the meta box data Link
Now that you’ve learned how to create custom post meta boxes in wordpress, it’s time to learn how to save post metadata.
Remember that smashing_post_meta_boxes_setup() function you created earlier? You need to modify that a bit. You’ll want to add the following code to it.
/* Save post meta on the 'save_post' hook. */
add_action( 'save_post', 'smashing_save_post_class_meta', 10, 2 );
/* Meta box setup function. */
function smashing_post_meta_boxes_setup() {
/* Add meta boxes on the 'add_meta_boxes' hook. */
add_action( 'add_meta_boxes', 'smashing_add_post_meta_boxes' );
/* Save post meta on the 'save_post' hook. */
add_action( 'save_post', 'smashing_save_post_class_meta', 10, 2 );
}
The new code you’re adding tells WordPress that you want to run a custom function on the save_post hook. This function will save, update, or delete your custom post meta boxes in wordpress.
When saving post meta, your function needs to run through a number of processes:
- Verify the nonce set in the meta box function.
- Check that the current user has permission to edit the post.
- Grab the posted input value from
$_POST
. - Decide whether the meta should be added, updated, or deleted based on the posted value and the old value.
I’ve left the following function somewhat generic so that you’ll have a little flexibility when developing your own meta boxes.
It is the final snippet of code that you’ll need to save the metadata for your custom post class meta box.
/* Save the meta box's post metadata. */
function smashing_save_post_class_meta( $post_id, $post ) {
/* Verify the nonce before proceeding. */
if ( !isset( $_POST['smashing_post_class_nonce'] ) || !wp_verify_nonce( $_POST['smashing_post_class_nonce'], basename( __FILE__ ) ) )
return $post_id;
/* Get the post type object. */
$post_type = get_post_type_object( $post->post_type );
/* Check if the current user has permission to edit the post. */
if ( !current_user_can( $post_type->cap->edit_post, $post_id ) )
return $post_id;
/* Get the posted data and sanitize it for use as an HTML class. */
$new_meta_value = ( isset( $_POST['smashing-post-class'] ) ? sanitize_html_class( $_POST['smashing-post-class'] ) : '' );
/* Get the meta key. */
$meta_key = 'smashing_post_class';
/* Get the meta value of the custom field key. */
$meta_value = get_post_meta( $post_id, $meta_key, true );
/* If a new meta value was added and there was no previous value, add it. */
if ( $new_meta_value && '' == $meta_value )
add_post_meta( $post_id, $meta_key, $new_meta_value, true );
/* If the new meta value does not match the old value, update it. */
elseif ( $new_meta_value && $new_meta_value != $meta_value )
update_post_meta( $post_id, $meta_key, $new_meta_value );
/* If there is no new meta value but an old value exists, delete it. */
elseif ( '' == $new_meta_value && $meta_value )
delete_post_meta( $post_id, $meta_key, $meta_value );
}
At this point, you can save, update, or delete the data in the “Post Class” meta box you created from the post editor screen.
When it comes to custom post meta boxes in WordPress, thinking outside the box can unlock extraordinary possibilities for content creation.
Creating custom post meta boxes in WordPress opens a world of possibilities for organizing, enriching, and customizing your content.
By following the steps outlined in this blog post, you can take control of your WordPress website, empower content creators, and provide a tailored editing experience.
So, unleash your creativity, dive into the world of custom post meta boxes in WordPress, and take your WordPress website to new heights of customization and functionality!
My partner and I absolutely love your blog and find almost all of your post’s to be precisely what I’m looking for. Would you offer guest writers to write content for you? I wouldn’t mind producing a post or elaborating on a few of the subjects you write concerning here. Again, awesome website!
My spouse and I stumbled over here from a different web page and thought I might check things out. I like what I see so now i am following you. Look forward to exploring your web page repeatedly.
Bookmarked!, I like it!