Create a Space theme for WordPress – 2021 – Part 11, Custom fields

Adding meta boxes.

All the code below goes in functions.php.

The first thing you need when adding meta boxes is to create an add action hook. This takes two parameters, the add_meta_boxes hook and the function to call when the action is triggered.

function launch_add_meta_boxes(){
    add_meta_box('launch_meta',// slug name
                 'launch information',// title
                 'launch_callback',// callback function
                 'launches'
                );
     };
     add_action('add_meta_boxes','launch_add_meta_boxes');

The meta boxes will display in the posts edit screen as below.

The callback function

The launch_add_meta_boxes() function then calls the WordPress function add_meta_box(). This takes several parameters including the title and, most importantly, the callback function that will display the input fields.

function launch_callback($post){
    wp_nonce_field( basename(__FILE__),'launches_nonce' );
    // get the post meta using the post id, returns an array
    $stored_meta = get_post_meta($post->ID);
?>
    <div>
        <div class="meta-row">
            <div class="meta-th">
                <label for="provider_id" class="row-title">Provider</label>
            </div>
            <div class="meta-td">
                <input type="text" name="provider_id" id="provider_id" value="<?php if (! empty ($stored_meta['provider_id'])) echo esc_attr($stored_meta['provider_id'][0]);?>"/>
            </div>
        </div>
    </div>
    <div>
        <div class="meta-row">
            <div class="meta-th">
                <label for="launch_date" class="row-title">Launch date</label>
            </div>
            <div class="meta-td">
                <input type="text" name="launch_date" id="launch_date" value="<?php if (! empty ($stored_meta['launch_date'])) echo esc_attr($stored_meta['launch_date'][0]);?>"/>
            </div>
        </div>
    </div>
<?php
}

The front end display

The data displays on the front end as below.

The meta save function

The final task is to safely save the inputted data to the database. this requires a range of security checks. There are two checks to stop the form from submitting if it is being autosaved or is a revision.

The main security feature is the use of a nonce field. For example, WordPress has a built-in nonce field generator. For the form to submit the nonce field generated here, has to match the value from another WordPress function that verifies its value. Above all this confirms that the submitted data is not coming from a hackers page.

wp_nonce_field( basename(__FILE__),'launches_nonce' );

The update post meta function is the one that actually submits the data to the database. It takes three parameters the post ID, the key, and the value. The value is derived from the input field using $_POST. Note the underscore and capitalization. This is a standard PHP variable that contains POSTED data from an input field. Not to be confused with the WordPress $post variable.

// save meta data to DB .............................................
    function meta_save($post_id){
        // security  .... all true or false checks
        $is_autosave = wp_is_post_autosave( $post_id);// true or false
        $is_revision = wp_is_post_revision( $post_id);
        $is_valid_nonce = ( isset( $_POST['launches_nonce'])&& wp_verify_nonce( $_POST['launches_nonce'], basename(__FILE__)))?'true': 'false';
       // Exits script if depending on save status
        if($is_autosave || $is_revision || !$is_valid_nonce ){
            return;
        };

        if (isset($_POST['provider_id'])){
            update_post_meta($post_id, 'provider_id',sanitize_text_field($_POST['provider_id']));
        }
        if (isset($_POST['launch_date'])){
             update_post_meta($post_id, 'launch_date',sanitize_text_field($_POST['launch_date']));
        };
        };
add_action('save_post', 'meta_save');

The final task is to add an add action hook that triggers the meta_save function when the page is updated.

Summary
Wordpress cutom fields tutorial
Article Name
Wordpress cutom fields tutorial
Description
How to create, save and display custom fields in WordPress.
Author
Publisher Name
Learn web design.co.uk
Publisher Logo