add_meta_box()为博客后台管理界面添加一个Meta模块

目录

描述

译文

add_meta_box在WordPress 2.5版本中被引入。插件开发者可通过该函数在Write Post,Write Page和Write Link编辑页面内添加版块。

原文

add_meta_box() 函数是在 WordPress 2.5 添加的,用来给插件开发者添加 Meta模块 到管理界面。 

This function should be called from the add_meta_boxes_{post_type} or 'add_meta_boxes' action. The former is preferable as it avoids triggering needless callbacks for other post types. These actions were introduced in Version 3.0; in prior versions, use 'admin_init' instead.

add_meta_box() 描述

用法

<?php
   add_meta_box
$id$title$callback$screen$context,
         
$priority$callback_args );
?>

add_meta_box() 用法

参数

$id

(string) (必填) Meta模块的 HTML“ID”属性

默认值: None

$title

(string) (必填) Meta模块的标题,对用户可见

默认值: None

$callback

(callback) (必填) 为Meta模块输出 HTML代码的函数

默认值: None

$screen

(string) (可选) The type of writing screen on which to show the edit screen section (examples include 'post','page','dashboard','link','attachment','custom_post_type','comment' where custom_post_type is the custom post type slug)

默认值: null

$context

(string) (可选) The part of the page where the edit screen section should be shown ('normal', 'advanced', or 'side'). (Note that 'side' doesn't exist before 2.7)

默认值: 'advanced'

$priority

(string) (可选) The priority within the context where the boxes should show ('high', 'core', 'default' or 'low')

默认值: 'default'

$callback_args

(array) (可选) Arguments to pass into your callback function. The callback will receive the $post object and whatever parameters are passed through this variable.

默认值: null

add_meta_box() 参数

返回值

None.

add_meta_box() 返回值

示例

Procedural

Here is an example that adds a custom section to the post and page editing screens:

/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */

<?php

/**
 * Adds a box to the main column on the Post and Page edit screens.
 */
function myplugin_add_meta_box() {

	$screens = array( 'post', 'page' );

	foreach ( $screens as $screen ) {

		add_meta_box(
			'myplugin_sectionid',
			__( 'My Post Section Title', 'myplugin_textdomain' ),
			'myplugin_meta_box_callback',
			$screen
		);
	}
}
add_action( 'add_meta_boxes', 'myplugin_add_meta_box' );

/**
 * Prints the box content.
 * 
 * @param WP_Post $post The object for the current post/page.
 */
function myplugin_meta_box_callback( $post ) {

	// Add a nonce field so we can check for it later.
	wp_nonce_field( 'myplugin_save_meta_box_data', 'myplugin_meta_box_nonce' );

	/*
	 * Use get_post_meta() to retrieve an existing value
	 * from the database and use the value for the form.
	 */
	$value = get_post_meta( $post->ID, '_my_meta_value_key', true );

	echo '<label for="myplugin_new_field">';
	_e( 'Description for this field', 'myplugin_textdomain' );
	echo '</label> ';
	echo '<input type="text" id="myplugin_new_field" name="myplugin_new_field" value="' . esc_attr( $value ) . '" size="25" />';
}

/**
 * When the post is saved, saves our custom data.
 *
 * @param int $post_id The ID of the post being saved.
 */
function myplugin_save_meta_box_data( $post_id ) {

	/*
	 * We need to verify this came from our screen and with proper authorization,
	 * because the save_post action can be triggered at other times.
	 */

	// Check if our nonce is set.
	if ( ! isset( $_POST['myplugin_meta_box_nonce'] ) ) {
		return;
	}

	// Verify that the nonce is valid.
	if ( ! wp_verify_nonce( $_POST['myplugin_meta_box_nonce'], 'myplugin_save_meta_box_data' ) ) {
		return;
	}

	// If this is an autosave, our form has not been submitted, so we don't want to do anything.
	if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
		return;
	}

	// Check the user's permissions.
	if ( isset( $_POST['post_type'] ) && 'page' == $_POST['post_type'] ) {

		if ( ! current_user_can( 'edit_page', $post_id ) ) {
			return;
		}

	} else {

		if ( ! current_user_can( 'edit_post', $post_id ) ) {
			return;
		}
	}

	/* OK, it's safe for us to save the data now. */
	
	// Make sure that it is set.
	if ( ! isset( $_POST['myplugin_new_field'] ) ) {
		return;
	}

	// Sanitize user input.
	$my_data = sanitize_text_field( $_POST['myplugin_new_field'] );

	// Update the meta field in the database.
	update_post_meta( $post_id, '_my_meta_value_key', $my_data );
}
add_action( 'save_post', 'myplugin_save_meta_box_data' );

Class

This is an example of how to add a meta box from inside a class

/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */

<?php

/**
 * Calls the class on the post edit screen.
 */
function call_someClass() {
    new someClass();
}

if ( is_admin() ) {
    add_action( 'load-post.php', 'call_someClass' );
    add_action( 'load-post-new.php', 'call_someClass' );
}

/** 
 * The Class.
 */
class someClass {

	/**
	 * Hook into the appropriate actions when the class is constructed.
	 */
	public function __construct() {
		add_action( 'add_meta_boxes', array( $this, 'add_meta_box' ) );
		add_action( 'save_post', array( $this, 'save' ) );
	}

	/**
	 * Adds the meta box container.
	 */
	public function add_meta_box( $post_type ) {
            $post_types = array('post', 'page');     //limit meta box to certain post types
            if ( in_array( $post_type, $post_types )) {
		add_meta_box(
			'some_meta_box_name'
			,__( 'Some Meta Box Headline', 'myplugin_textdomain' )
			,array( $this, 'render_meta_box_content' )
			,$post_type
			,'advanced'
			,'high'
		);
            }
	}

	/**
	 * Save the meta when the post is saved.
	 *
	 * @param int $post_id The ID of the post being saved.
	 */
	public function save( $post_id ) {
	
		/*
		 * We need to verify this came from the our screen and with proper authorization,
		 * because save_post can be triggered at other times.
		 */

		// Check if our nonce is set.
		if ( ! isset( $_POST['myplugin_inner_custom_box_nonce'] ) )
			return $post_id;

		$nonce = $_POST['myplugin_inner_custom_box_nonce'];

		// Verify that the nonce is valid.
		if ( ! wp_verify_nonce( $nonce, 'myplugin_inner_custom_box' ) )
			return $post_id;

		// If this is an autosave, our form has not been submitted,
                //     so we don't want to do anything.
		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) 
			return $post_id;

		// Check the user's permissions.
		if ( 'page' == $_POST['post_type'] ) {

			if ( ! current_user_can( 'edit_page', $post_id ) )
				return $post_id;
	
		} else {

			if ( ! current_user_can( 'edit_post', $post_id ) )
				return $post_id;
		}

		/* OK, its safe for us to save the data now. */

		// Sanitize the user input.
		$mydata = sanitize_text_field( $_POST['myplugin_new_field'] );

		// Update the meta field.
		update_post_meta( $post_id, '_my_meta_value_key', $mydata );
	}


	/**
	 * Render Meta Box content.
	 *
	 * @param WP_Post $post The post object.
	 */
	public function render_meta_box_content( $post ) {
	
		// Add an nonce field so we can check for it later.
		wp_nonce_field( 'myplugin_inner_custom_box', 'myplugin_inner_custom_box_nonce' );

		// Use get_post_meta to retrieve an existing value from the database.
		$value = get_post_meta( $post->ID, '_my_meta_value_key', true );

		// Display the form, using the current value.
		echo '<label for="myplugin_new_field">';
		_e( 'Description for this field', 'myplugin_textdomain' );
		echo '</label> ';
		echo '<input type="text" id="myplugin_new_field" name="myplugin_new_field"';
                echo ' value="' . esc_attr( $value ) . '" size="25" />';
	}
}

Callback args

The $callback_args array will be passed to the callback function as the second argument. The first argument is the post's $post object.

/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */

// This function adds a meta box with a callback function of my_metabox_callback()
function add_my_meta_box() {
     $var1 = 'this';
     $var2 = 'that';
     add_meta_box( 
           'metabox_id',
           'Metabox Title',
           'my_metabox_callback',
           'page',
           'normal',
           'low', 
           array( 'foo' => $var1, 'bar' => $var2)
      );
}

// $post is an object containing the current post (as a $post object)
// $metabox is an array with metabox id, title, callback, and args elements. 
// The args element is an array containing your passed $callback_args variables.

function my_metabox_callback ( $post, $metabox ) {
     echo 'Last Modified: ' . $post->post_modified;        // outputs last time the post was modified
     echo $metabox['args']['foo'];                         // outputs 'this'
     echo $metabox['args']['bar'];                         // outputs 'that'
     echo get_post_meta( $post->ID, 'my_custom_field', true ); // outputs value of custom field
}

add_meta_box() 示例

源文件

add_meta_box() 函数的代码位于 wp-admin/includes/template.php.

/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */
/**
 * Add a meta box to an edit form.
 *
 * @since 2.5.0
 *
 * @global array $wp_meta_boxes
 *
 * @param string           $id            String for use in the 'id' attribute of tags.
 * @param string           $title         Title of the meta box.
 * @param callback         $callback      Function that fills the box with the desired content.
 *                                        The function should echo its output.
 * @param string|WP_Screen $screen        Optional. The screen on which to show the box (like a post
 *                                        type, 'link', or 'comment'). Default is the current screen.
 * @param string           $context       Optional. The context within the screen where the boxes
 *                                        should display. Available contexts vary from screen to
 *                                        screen. Post edit screen contexts include 'normal', 'side',
 *                                        and 'advanced'. Comments screen contexts include 'normal'
 *                                        and 'side'. Menus meta boxes (accordion sections) all use
 *                                        the 'side' context. Global default is 'advanced'.
 * @param string           $priority      Optional. The priority within the context where the boxes
 *                                        should show ('high', 'low'). Default 'default'.
 * @param array            $callback_args Optional. Data that should be set as the $args property
 *                                        of the box array (which is the second parameter passed
 *                                        to your callback). Default null.
 */
function add_meta_box( $id, $title, $callback, $screen = null, $context = 'advanced', $priority = 'default', $callback_args = null ) {
	global $wp_meta_boxes;

	if ( empty( $screen ) )
		$screen = get_current_screen();
	elseif ( is_string( $screen ) )
		$screen = convert_to_screen( $screen );

	$page = $screen->id;

	if ( !isset($wp_meta_boxes) )
		$wp_meta_boxes = array();
	if ( !isset($wp_meta_boxes[$page]) )
		$wp_meta_boxes[$page] = array();
	if ( !isset($wp_meta_boxes[$page][$context]) )
		$wp_meta_boxes[$page][$context] = array();

	foreach ( array_keys($wp_meta_boxes[$page]) as $a_context ) {
		foreach ( array('high', 'core', 'default', 'low') as $a_priority ) {
			if ( !isset($wp_meta_boxes[$page][$a_context][$a_priority][$id]) )
				continue;

			// If a core box was previously added or removed by a plugin, don't add.
			if ( 'core' == $priority ) {
				// If core box previously deleted, don't add
				if ( false === $wp_meta_boxes[$page][$a_context][$a_priority][$id] )
					return;

				/*
				 * If box was added with default priority, give it core priority to
				 * maintain sort order.
				 */
				if ( 'default' == $a_priority ) {
					$wp_meta_boxes[$page][$a_context]['core'][$id] = $wp_meta_boxes[$page][$a_context]['default'][$id];
					unset($wp_meta_boxes[$page][$a_context]['default'][$id]);
				}
				return;
			}
			// If no priority given and id already present, use existing priority.
			if ( empty($priority) ) {
				$priority = $a_priority;
			/*
			 * Else, if we're adding to the sorted priority, we don't know the title
			 * or callback. Grab them from the previously added context/priority.
			 */
			} elseif ( 'sorted' == $priority ) {
				$title = $wp_meta_boxes[$page][$a_context][$a_priority][$id]['title'];
				$callback = $wp_meta_boxes[$page][$a_context][$a_priority][$id]['callback'];
				$callback_args = $wp_meta_boxes[$page][$a_context][$a_priority][$id]['args'];
			}
			// An id can be in only one priority and one context.
			if ( $priority != $a_priority || $context != $a_context )
				unset($wp_meta_boxes[$page][$a_context][$a_priority][$id]);
		}
	}

	if ( empty($priority) )
		$priority = 'low';

	if ( !isset($wp_meta_boxes[$page][$context][$priority]) )
		$wp_meta_boxes[$page][$context][$priority] = array();

	$wp_meta_boxes[$page][$context][$priority][$id] = array('id' => $id, 'title' => $title, 'callback' => $callback, 'args' => $callback_args);
}

add_meta_box() 源文件