Can someone guide me on how to create a custom meta box in WordPress and save the entered data?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our W3Make Forum to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
You must perform the following actions in order to create a custom meta box in WordPress and save the entered information:
First, sign up for the Meta Box.
Use the add_meta_box function in the functions.php file of your theme or a custom plugin to register your custom meta box. The meta box ID, title, callback function, associated post type, and context are among the arguments this function accepts. Example:
function custom_meta_box() {
add_meta_box(
'custom_meta_box',
'Custom Meta Box',
'custom_meta_box_callback',
'post',
'normal',
'default'
);
}
add_action('add_meta_boxes', 'custom_meta_box');
Create the Meta Box Content in Step 2
You’ll define the content of your meta box in the callback function you provided in the step before (custom_meta_box_callback in this example). Usually, this consists of HTML input fields or other form components. Here is a simple illustration using an input field:
function custom_meta_box_callback($post) {
$value = get_post_meta($post->ID, 'custom_meta', true);
?>
Custom Field:
<input type="text" id="custom_meta" name="custom_meta" value="">
<?php
}
Save the Meta Box Data in Step 3
You must hook into the save_post action in order to save the information entered in the custom meta field. The custom_meta field's value will be saved in the example below:
function save_custom_meta_box_data($post_id) {
if (array_key_exists('custom_meta', $_POST)) {
update_post_meta(
$post_id,
'custom_meta',
sanitize_text_field($_POST['custom_meta'])
);
}
}
add_action('save_post', 'save_custom_meta_box_data');
Using the’sanitize_text_field()’ function to sanitize the input, this function then uses the ‘update_post_meta’ function to save it. It first checks to see if the custom_meta field is present in the ‘$_POST’ array.
I’m done now! Your custom meta box has been registered, and the information you submitted will now be preserved and linked to the relevant post. These examples can be expanded upon and modified to fit your unique needs.