Metabox Tutorial – More Examples

Share this Article

In this tutorial we will create more metaboxes. If you will execute all metaboxes code into your wordpress programming then surely you will understand all about this wordpress metabox tutorial.

You can add this code into your custom plugin code or add inside activated theme functions.php file.

Example #1

Custom Dashboard Widget

We will create a dashboard widget with some information and links.

/**
 * Register dashboard widget.
 */

function owt_custom_dashboard_widgets()
{
    wp_add_dashboard_widget('owt_custom_help_widget', 'OWT Support', 'owt_custom_dashboard_help');
}

add_action('wp_dashboard_setup', 'owt_custom_dashboard_widgets');

function owt_custom_dashboard_help()
{
    echo '<p>Welcome to Custom OWT Theme! Need help? Contact the developer <a href="mailto:yourusername@gmail.com">here</a>. For WordPress Metabox Tutorials visit: <a href="https://onlinewebtutorblog.com/wordpress-metabox/what-is-a-wordpress-metabox/" target="_blank">Online Web Tutor</a></p>';
}

Output

Example #2

Create Custom Metabox for Add Page / Edit Page. Metabox should be at the top of all metaboxes.

/**
 * Register meta box(es).
 */
function owt_register_post_meta_box()
{
    add_meta_box('page-meta-box-id', __('My Page Meta Box', 'textdomain'), 'owt_my_display_callback', 'page', 'side' ,'high');
}
add_action('add_meta_boxes', 'owt_register_post_meta_box');

/*
 * Custom metabox callback function 
 */
function owt_my_display_callback($post)
{
?>
    <p>
        <input type="text" placeholder="Author name" name="author_name" class="widefat" size="20" value="<?php echo esc_attr(get_post_meta(get_the_ID(), 'owt_author_name', true)); ?>">
    </p>
    <p>
        <textarea class="widefat" name="author_desc" placeholder="Add your description"><?php echo esc_attr(get_post_meta(get_the_ID(), 'owt_author_description', true)); ?></textarea>
    </p>
<?php
}

/**
 *  Save metabox inputs
 */
function owt_save_custom_meta_box_content($post_id)
{
    $author_name = $_POST['author_name'];
    $author_desc = $_POST['author_desc'];

    update_post_meta($post_id, 'owt_author_name', $author_name);
    update_post_meta($post_id, 'owt_author_description', $author_desc);
}

add_action('save_post', 'owt_save_custom_meta_box_content');

Above code will register a custom metabox inside Add New Page / Edit Page. Metabox will be at side position. Metabox priority will be high among all metaboxes.

Output

Was this post helpful?

PHP Web Development Courses on Offer in just $4
PHP Web Development Courses on Offer in just $4