How to add custom fields to quick edit in WordPress
Home » BLOG » WordPress » How to add custom fields to quick edit in WordPress

How to add custom fields to quick edit in WordPress

category:  WordPress
[Sassy_Social_Share] 8 min read

A quick edit is one of useful feature from WordPress. It is useful when you just want to add or edit a small changes for your pages or posts without loading the whole content editor page.

quick edit WordPress
Figure: quick edit in WordPress

By default, quick edit allows you to change the title, slug, published date, password, categories, template, tags, allow comments, allow pings, post status and post sticky setting. But if you have your own custom fields and want to add them into the quick edit, how can you do that?

Add custom fields (skip this step if you already had your custom fields)

I have the custom fields for my project post type. If you want to use the same custom fields and project post type as mine, you can download my plugin below and activate it in your WordPress site.

Custom Fields Tutorial - source code plugin (0 downloads)

Below is my custom fields for the project post type which are project image, description, time spent, website and published date.

custom fields
Figure: Custom fields for my project post type

Step 1: Add custom fields to the posts management page

We will create our own plugin for this tutorial. First, we create a new quick_edit_box folder under the WordPress plugins folder.

Next, we create a new quick_edit_box.php under the quick_edit_box folder. The quick_edit_box.php is our main plugin file for our plugin.

Add the code below in the quick_edit_box.php.

<?php
/*
    Plugin Name: Add Custom Fields To Quick Edit Box
    Plugin URI: https://applerinquest.com/how-to-add-custom-fields-to-your-wordpress/
    Description: Add custom fields of the project post type to quick edit box
    Version: 1.0.0
    Author: Apple Rinquest
    Author URI: https://applerinquest.com/
    Text Domain: your-textdomain
*/

if (!defined('ABSPATH')) exit; // Exit if accessed directly

Now, we will add some custom fields we want to display on the posts management page. I will add the project image, website and published date.

To do that, add the code below into the quick_edit_box.php.

/**
 * Add custom fields to the posts management page
 */
if (!function_exists('wpar_add_new_columns')) {
    function wpar_add_new_columns($columns)
    {
        $new_columns = array(
            '_proj-image' => esc_html__('Image', 'your-textdomain'),
            '_proj-website' => esc_html__('Website', 'your-textdomain'),
            '_proj-published' => esc_html__('Published Date', 'your-textdomain'),
        );

        // return the columns array back
        return array_merge($columns, $new_columns);
    }

    // https://developer.wordpress.org/reference/hooks/manage_post_type_posts_columns/
    // manage_{$post_type}_posts_columns action hook
    // $post_type is a post type key in the register_post_type().
    // I have mms_project_cpt as my projectd post type.
    add_filter('manage_mms_project_cpt_posts_columns',  'wpar_add_new_columns');
}
add custom fields to admin page
Figure: add new custom field into the posts management page

Important note, DO NOT remove the title column since the quick edit feature attaches to the title column.

We use the manage_{$post_type}_posts_columns filter hook for adding the custom fields to the default columns array. This filter hook will hook the new columns to our project post type only. Now, our custom fields should show on the posts management page.

Related filter and action hooks

Step 2: Populate the custom field value from the database

The custom fields we just added from Step 1, they don’t show any value on the posts management page. So in this step 2, we will populate the custom field value from database. To do that, add the code below into the quick_edit_box.php

/**
 * Populate custom field value
 */
if (!function_exists('wpar_custom_columns')) {
    function wpar_custom_columns($column, $post_id)
    {
        switch ($column) {
            case '_proj-image':
                $proj_image = get_post_meta($post_id, '_proj-image', true);
                echo '<img src="' . esc_html__($proj_image) . '" alt="" style="width: 200px;">';
                break;
            case '_proj-website':
                $proj_website = get_post_meta($post_id, '_proj-website', true);
                echo '<a href="' . esc_url($proj_website) . '" target="_blank">' . esc_url($proj_website) . '</a>';
                break;
            case '_proj-published':
                $proj_published = get_post_meta($post_id, '_proj-published', true);
                echo esc_html__($proj_published);
                break;
            default:
                break;
        }
    }

    // https://codex.wordpress.org/Plugin_API/Action_Reference/manage_$post_type_posts_custom_column
    add_action('manage_mms_project_cpt_posts_custom_column', 'wpar_custom_columns', 10, 2);
}

We use manage_{$post_type}_posts_custom_column action hook for our project post type. Also we use get_post_meta() for getting the data from wp_postmeta table while is a WordPress table that stores the custom fields data.

display the custom field value on the page
Figure: display the custom field value on the page

Step 3: Show the custom fields in the quick edit box

We use quick_edit_custom_box action hook for adding the custom field into the quick edit box.

Important note, the quick_edit_custom_box action hook fires once for each column.

Note that, the quick_edit_custom_box action hook won’t fire unless the custom fields are added into the posts management page which is step 1.

In the quick edit box, I will add the project website field only. To do that, add the code below into the quick_edit_box.php

/**
 * Add custom fields to the quick edit box
 * 
 * quick_edit_custom_box allows to add HTML in Quick Edit
 */
if (!function_exists('wpar_add_quick_edit')) {
    // $column_name stores only the custom fields
    function wpar_add_quick_edit($column_name, $post_type)
    {

        if (!($column_name === '_proj-website')) return;

        // # Note
        // The class names that use with fieldset tag, 
        // it can be inline-edit-col-left, inline-edit-col-center and inline-edit-col-right.
        // 
        // # Trick: You can use the inspection tool from your browser to see what classes the admin page uses in the quick edit box.
?>

        <?php
        switch ($column_name) {
            case '_proj-website':

                // We keeps all our custom fields inside the <fieldset>
                // # a first column then print out the fieldset tag here.
                echo '<fieldset class="inline-edit-col-right" style="border: 1px solid #dddddd;">
                        <legend style="font-weight: bold; margin-left: 10px;">Project Custom Fields:</legend>
                        <div class="inline-edit-col">';


                // # note that, wp_nonce_field() must add it here at the first custom column. DO NOT add outside the switch().
                // Otherwise wp_nonce_field() will render every time that quick_edit_custom_box action hook is called for each column.
                wp_nonce_field('wpar_q_edit_nonce', 'wpar_nonce');
                echo '<label class="alignleft" style="width: 100%;">
                        <span class="title">' . __('Website', 'your-textdomain') . '</span>
                        <span class="input-text-wrap"><input type="url" name="' . $column_name . '" value="" style="width: 100%;"></span>
                        <span style="font-style: italic;color:#999999; text-align:right; display: inherit;">Enter the website URL</span>
                      </label>';
                echo '<br><br>';
                // # a last column then print out the end tags of fieldset here.      
                echo '</div></fieldset>';
                break;
            default:
                break;
        }
    }

    // https://codex.wordpress.org/Plugin_API/Action_Reference/quick_edit_custom_box
    add_action('quick_edit_custom_box',  'wpar_add_quick_edit', 10, 2);
}
add custom fields in the quick edit box
Figure: add custom fields in the quick edit box

Notice that, no data of project website field is displayed in the quick edit box yet. Next step, we do save the data from the quick edit box and populate the data via JavaScript.

Step 4: Save the custom field value from the quick edit box

In order to save the changes for the custom fields from the quick edit box, we will use save_post_{$post_type} action hook. This action hook will apply to our project post type only.

For saving the custom field value, add the code below in the quick_edit_box.php.

/**
 * Save the custom field value from the quick edit box 
 */
if (!function_exists(('wpar_quick_edit_save'))) {
    function wpar_quick_edit_save($post_id)
    {
        // # For quick edits use $_POST for storing the data.

        // If it is autosave, we don't do anything.
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
            return $post_id;


        // check user capabilities
        if (
            !current_user_can('edit_post', $post_id)
        ) {
            return;
        }

        // check nonce
        if (
            !wp_verify_nonce($_POST['wpar_nonce'], 'wpar_q_edit_nonce')
        ) {
            return;
        }

        // update the website
        if (
            isset($_POST['_proj-website'])
        ) {
            update_post_meta($post_id, '_proj-website', $_POST['_proj-website']);
        }
    }

    // https://developer.wordpress.org/reference/hooks/save_post_post-post_type/
    add_action('save_post_mms_project_cpt', 'wpar_quick_edit_save');
}

Now, after changing the website value from the quick edit box and hits Update button. Your new website URL should be saved into the database.

Step 5: Populate the custom field value at the quick edit box

In this step, we will use the jQuery to help us. The concept is the same as the inline editor implementation by jQuery. It is simple if you know how to customize the jQuery or javascript. Let’s me explain more.

Data table structure

Use the inspection tool from browser
Figure: Use the inspection tool from the browser

From the image above, I use the inspection tool from the browser(F12 for Windows). You will see all posts are rendered inside the <tbody> along with “the-list” id.

Then each post is rendered on each <tr> along with “post-176” id which 176 is my post id. Your post id will be difference from me.

After clicking on quick edit menu, the data row is hidden and new edit row is appended.
Figure: After clicking on quick edit menu, the data row is hidden and new edit row is appended.

What idea we will do

What we will do, we will use the jQuery to find the website field from the hidden <tr id=”post-176″>. Once we find the website field, we will get its value. Then we will find the website input field from the <tr id=”edit-176″> which is the quick edit box. Once we find the website input field, we will assign the value that we get from the hidden row to the input field. And that’s it.

Add the JS code

Now, add the code below into the quick_edit_box.php

<?php
/**
 * Populate the custom field values at the quick edit box using Javascript
 */
if (!function_exists('wpar_quick_edit_js')) {
    function wpar_quick_edit_js()
    {
        // # check the current screen
        // https://developer.wordpress.org/reference/functions/get_current_screen/
        $current_screen = get_current_screen();

        /*
         * ****************************************
         * # List of default screen ID in WordPress
         * ****************************************
        PAGE               $SCREEN_ID           FILE
        -----------------  -------------------  -----------------------
        Media Library      upload               upload.php
        Comments           edit-comments        edit-comments.php
        Tags               edit-post_tag        edit-tags.php
        Plugins            plugins              plugins.php
        Links              link-manager         link-manager.php
        Users              users                users.php
        Posts              edit-post            edit.php
        Pages              edit-page            edit.php
        Edit Site: Themes  site-themes-network  network/site-themes.php
        Themes             themes-network       network/themes
        Users              users-network        network/users
        Edit Site: Users   site-users-network   network/site-users
        Sites              sites-network        network/sites
        
        If you use the custom post type just like me, you can print out the get_current_screen() object
        for checking what screen ID do you need for the next checking.
        My current screen ID of project post type is "edit-mms_project_cpt".
        
        var_dump($current_screen);
        exit;
        */

        if ($current_screen->id != 'edit-mms_project_cpt' || $current_screen->post_type !== 'mms_project_cpt')
            return;


        // # Make sure jQuery library is loaded because we will use jQuery for populate our custom field value.
        wp_enqueue_script('jquery');
        ?>


        <!-- add JS script -->
        <script type="text/javascript">
            jQuery(function($) {

                // we create a copy of the WP inline edit post function
                var $wpar_inline_editor = inlineEditPost.edit;

                // Note: Hooking inlineEditPost.edit must be done in a JS script, loaded after wp-admin/js/inline-edit-post.js
                // then we overwrite the inlineEditPost.edit function with our own code
                inlineEditPost.edit = function(id) {

                    // call the original WP edit function 
                    $wpar_inline_editor.apply(this, arguments);


                    // ### start: add our custom functionality below  ###

                    // get the post ID
                    var $post_id = 0;
                    if (typeof(id) == 'object') {
                        $post_id = parseInt(this.getId(id));
                    }

                    // if we have our post
                    if ($post_id != 0) {
                        // tips: use the inspecttion tool to help you see the HTML structure on the edit page.

                        // explanation: 
                        // On the posts management page, all posts will render inside the <tbody> along with "the-list" id.
                        // Then each post will render on each <tr> along with "post-176" which 176 is my post ID. Your will be difference.
                        // When the quick edit menu is clicked on the "post-176", the <tr> will be set as hide(display:none)
                        // and the new <tr> along with "edit-176" id will be appended after <tr> which is hidden.
                        // What we will do, we will use the jQuery to find the website value from the hidden <tr>. 
                        // Get that value and assign to the website input field on the quick edit box.
                        // 
                        // The concept is the same when you create the inline editor by jQuery manually.

                        // define the edit row
                        var $edit_row = $('#edit-' + $post_id);
                        var $post_row = $('#post-' + $post_id);

                        // get the data
                        var $website = $('.column-_proj-website', $post_row).text();

                        // populate the data
                        $(':input[name="_proj-website"]', $edit_row).val($website);
                    }

                    // ### end: add our custom functionality below  ###
                }

            });
        </script>
<?php
    }

    // https://developer.wordpress.org/reference/hooks/admin_print_footer_scripts-hook_suffix/
    add_action('admin_print_footer_scripts-edit.php', 'wpar_quick_edit_js');
}

Now, the custom field value should show on the quick edit box.

Download full source code plugin for quick edit box tutorial

You can download a full source code plugin for quick edit box tutorial below. If you want to activate and use them on your WordPress, you must download another plugin that I mention before step 1. That plugin will create the project post type and custom fields that I mention in this tutorial.

Quick Edit Box WordPress (0 downloads)

And that’s it for today.