How to add a metabox in Wordpress?

2019-06-13 02:39发布

<?php
function prfx_custom_meta()
{
add_meta_box(
    'some_meta_box_name'
    ,__( 'Some Meta Box Headline', 'plugin_textdomain' )
    ,'render_meta_box_content' //this is callback function.
    ,'post_type'
    ,'advanced'
    ,'high'
);

}
add_action( 'add_meta_boxes', 'prfx_custom_meta' );
?>

I used the above code to create a metabox in Wordpress. But , for that code it doesn't showing up couldn't find the solution. kindly suggest any ideas for that problem .

标签: wordpress
1条回答
爷的心禁止访问
2楼-- · 2019-06-13 03:28

It all depends on where you want the metabox to appear.

If you want it to appear on posts then you need to use

if ( ! function_exists( 'add_post_metabox' ) ){
    function add_post_metabox(){
        add_meta_box('post-meta', esc_html__('My Metabox', 'mytheme'), 'My_Metabox_function', 'post', 'side', 'low');
    }
}

add_action('admin_init', 'add_post_metabox');

And then create metabox with

if ( ! function_exists( 'My_Metabox_function' ) ){
    function My_Metabox_function( $post ){
        //metabox layout and variables here
    }
}

if ( ! function_exists( 'My_Metabox_save_function' ) ){
    function My_Metabox_save_function($post_id){
        global $post;
        if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ){
                return $post_id;
            } else{
                //do save here
            }
        }
    }


add_action( 'save_post', 'My_Metabox_save_function' );

If you want it on page then you can create it like above but with page instead of post

if ( ! function_exists( 'add_page_metabox' ) ){
    function add_page_metabox(){
        add_meta_box('page-meta', esc_html__('My Metabox on Page', 'mytheme'), 'My_Metabox_page_function', 'page', 'normal', 'high');
    }
}

add_action('add_meta_boxes', 'add_page_metabox');

You can hook to admin_init of add_meta_boxes hooks. See here for more explanation.

You can put it in your functions.php file or you can set it in separate .php file and call it in functions.php with something like:

require_once( get_template_directory(). '/include/metaboxes.php' );

This will include metaboxes.php that are located in the /include directory of your theme.

查看更多
登录 后发表回答