CodeIn House

  • Laravel
  • WordPress
  • jQuery
  • Javascript
  • Contact
Home   WordPress   WordPress MetaBox Tutorial – How to Handle WordPress C ...

WordPress MetaBox Tutorial – How to Handle WordPress Custom Meta Box Multiple Fields ?

August 26, 2018 by SNK

In this WordPress meta box tutorial we are going see how to handle WordPress custom meta box multiple fields. We can create one meta box and unlimited fields to it and save it into database.

Data are stored in a form of an array serialized by WordPress itself. So, that later we can fetch those details in array form.

Also we will learn how WordPress saves meta box values in database and how can we optimize it.

let’s get started.

What are we going to do ?

    1. Create New Meta box in “Add new Post Section” .
    2. Create three fields First Name, Last Name and Email.
    3. Save it into database.
    4. Fetch the Multiple Values in the Front End.
    5. Knowing the difference between creating multiple meta boxes and single meta box with multiple fields.

Step 1 : Add New Meta-Box Inside Add new Post Section.

lets assume that we are going to add personal details ( like first name, last name and email ) fields in “Add new Post” section of WordPress. We are going to create one meta box named "pdetails" put all 3 fields inside the meta box and try to save it into the database.

Create New Metabox
PHP
1
2
3
4
5
6
7
8
9
10
function pdetails_meta_box() {
add_meta_box('pdetails','Personal Details','pdetails_callback','post');
}
add_action('add_meta_boxes','pdetails_meta_box');
 
function pdetails_callback( $post ) {
 
wp_nonce_field('pdetails_save','pdetails_meta_box_nonce');
$pdetails =  get_post_meta($post->ID,'_pdetails_key',false);
}

It you check Add New Post section Meta-Box with the title “Personal Details” should appear but no any fields inside. In next step we are going to add three new fields as we have mentioned above.We are going to make changes in same pdetails_callback function that we have above.

 

Step 2 : Create three fields First Name, Last Name and Email Inside Metabox

Add Personal Detail Fields
PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function pdetails_callback( $post ) {
 
wp_nonce_field('pdetails_save','pdetails_meta_box_nonce');
$pdetails =  get_post_meta($post->ID,'_pdetails_key',false);
 
?>
 
    <label for="">Enter First Name</label>
    <input type="text" name="first_name_field" placeholder="Enter First Name" value="<?php echo $pdetails[0]['first_name']; ?>">
    <br>
    <label for="">Enter Last Name</label>
    <input type="text" name="last_name_field" placeholder="Enter last Name" value="<?php echo $pdetails[0]['last_name']; ?>">
    <br>
    <label for="">Enter Email</label>
    <input type="text" name="email_field" placeholder="Enter Email" value="<?php echo $pdetails[0]['email']; ?>">
    <?php
}

If you again reload the page and check then, you will find Fields inside the Personal Details Meta box Section.

If you try to save it,  it wont get saved because, we haven’t wrote the function to save into database. Lets save those information into database in the next step.

Step 3 : Save Metabox Field Values in the Database

If you have noticed that inside pdetails_callback function we have wp_nonce_field(); function with the arguments. It is the process that WordPress uses for better security and mechanism to save into the database.

First argument is the action which is pdetails_save which required to save the meta box values into database and another argument checks whether the data is coming from the correct place or not. This is required for the security measure. Lets use pdetails_save function to save our data into database.

Saving MetaBox Data into Database
PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
function pdetails_save( $post_id ) {
 
if( ! isset($_POST['pdetails_meta_box_nonce'])) {
return;
}
 
if( ! wp_verify_nonce( $_POST['pdetails_meta_box_nonce'], 'pdetails_save') ) {
return;
}
 
if( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) {
return;
}
 
if( ! current_user_can('edit_post', $post_id)) {
return;
}
 
$personal_details = [
    'first_name' => $_POST['first_name_field'],
            'last_name' => $_POST['last_name_field'],
            'email' =>   $_POST['email_field']
    ];
 
 
 
update_post_meta( $post_id,'_pdetails_key', $personal_details );
}
add_action('save_post','pdetails_save');

Reload and refresh, the data have been now saved into database and now displaying in the form as well. Lets proceed to next.

Step 4 : Fetch the Multiple Values in the Front End

Put this small function inside functions.php

Library Function to Fetch meta box value
PHP
1
2
3
4
5
6
7
8
function get_personal_details($array_key) {
 
/**
* Fetch the value of metabox and return value according to user param
*/
    $personal_details = get_post_meta($post->ID,'_pdetails_key',false);
    return $personal_details[0][$array_key];
}

Now you can use echo get_personal_details('first_name'); to printout the first_name from the meta box anywhere in your website.

Note :- first_name is the key which is used in step 3 in $personal_details array and not the one in the form

Step 5 : Knowing the difference between creating multiple meta boxes and single Meta Box with Multiple Fields

If you check in your database, the data are saved on the basic of the key provided in the update_post_meta function(); which in our case is _pdetails_key.

saved meta key and value

If you look at the above picture we have one entry that we just saved. Many other beginner developers out there make multiple meta-boxes and finally results in multiple values saved in the database.

No, there is not any problem creating multiple meta boxes or saving in the database. It is completely fine if it is a business website and you dont have to update it frequently.

But, what if its a blog ? or a page that need to update regular and need to post regularly. Now lets, calculate.

1 Post have 3 Meta boxes = 3 new Entries to Post Meta section.

300 Post have 3 meta boxes = 900 New Entries to Post Meta section.

I guess for blog 300 posts is just a low number. Big sites have more than 10000 of post in their website. Guess what happens ?

It is where now your website starts to run slow.

With this method you can have multiple fields inside one meta box

1 Post have 1 meta box = Unlimited Entries in the form of text.

WordPress have fine ability to serialize the data while fetching from database, so that we could easily get those data in form of array.

So instead of using multiple meta box use one meta box to store unlimited amount of data per post. This way we are going to optimize our database for future and protect our website from running and loading slow.

If you liked this WordPress meta box tutorial on handling multiple fields in meta box, please do share and if any problem feel free to contact us via comments or contact page.

SHARE ON
Buffer

Enjoyed this article?

Like us on

WordPress add meta box wordpress add multiple meta boxes wordpress how to add custom meta field in wordpress wordpress add metabox to page wordpress add multiple custom meta boxes wordpress meta box tutorial

Avatar for SNK

About SNK

Hello Welcome to my Blog. I develop Websites Using Laravel Framwork & WordPress. Get Latest updates on Facebook | Twitter

Leave a Reply Cancel reply

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

Get Connected !! With Us

TOP POSTS

  • How to Setup Spring MVC Project From Scratch in Intellij IDEA ?
  • Spring Configuration Class in JAVA [Class VS XML Config]
  • Annotations Based Configuration in Spring Framework
  • How to Configure Spring Framework with XML Configurations?
  • How to Remove Project Name from URL in JSP Project in Intellij IDEA ?

TUTORIALS TILL DATE

  • September 2022 (6)
  • June 2021 (7)
  • October 2020 (5)
  • September 2020 (6)
  • September 2018 (14)
  • August 2018 (3)
  • July 2018 (4)
  • March 2018 (8)
  • February 2018 (5)
  • January 2018 (1)
  • December 2017 (2)
  • August 2017 (8)
  • May 2017 (1)
  • April 2017 (1)
  • March 2017 (4)
  • February 2017 (3)
  • January 2017 (4)

CATEGORIES

  • Angular (2)
  • CSS3 (3)
  • D3 (3)
  • HTML5 (7)
  • JAVA (11)
  • Javascript (20)
  • jQuery (8)
  • Laravel (35)
  • Others (3)
  • PHP (11)
  • Spring (2)
  • WordPress (10)

Top Categories

  • Angular
  • CSS3
  • D3
  • HTML5
  • JAVA
  • Javascript
  • jQuery
  • Laravel
  • Others
  • PHP
  • Spring
  • WordPress

Get in Touch

DMCA.com Protection Status

Recent Articles

  • How to Setup Spring MVC Project From Scratch in Intellij IDEA ?
  • Spring Configuration Class in JAVA [Class VS XML Config]
  • Annotations Based Configuration in Spring Framework
  • How to Configure Spring Framework with XML Configurations?
  • How to Remove Project Name from URL in JSP Project in Intellij IDEA ?

© 2012-22 CodeIn House.  •  All Rights Reserved.