函数文档

wp_add_dashboard_widget()

💡 云策文档标注

概述

wp_add_dashboard_widget() 函数用于在 WordPress 仪表盘中添加新的小工具。它基于 add_meta_box() 实现,允许开发者自定义小工具的 ID、标题、内容回调函数等参数,并支持控制回调和上下文位置设置。

关键要点

  • 函数接受多个参数:$widget_id(小工具 ID)、$widget_name(标题)、$callback(内容回调函数,需输出内容)、$control_callback(可选控制回调)、$callback_args(可选回调参数数组)、$context(可选上下文位置,如 'normal'、'side'、'column3'、'column4')、$priority(可选优先级,如 'high'、'core'、'default'、'low')。
  • 内部处理包括:自动合并私有回调参数、检查用户权限以启用控制回调、根据特定小工具 ID 自动设置上下文和优先级(如 'dashboard_quick_press' 强制为 'side')。
  • 函数最终调用 add_meta_box() 将小工具添加到当前屏幕,适用于仪表盘界面。
  • 注意事项:$callback_args 参数作为第二个参数传递给回调函数,第一个参数通常为空(仪表盘无屏幕对象);对于国际化,$widget_name 应使用翻译函数如 __()。
  • 替代方案:如需更灵活的位置控制,可直接使用 add_meta_box() 并指定 'dashboard' 作为屏幕。

代码示例

function wpdocs_add_dashboard_widgets() {
    wp_add_dashboard_widget( 'dashboard_widget', 'Example Dashboard Widget', 'dashboard_widget_function' );
}
add_action( 'wp_dashboard_setup', 'wpdocs_add_dashboard_widgets' );

function dashboard_widget_function( $post, $callback_args ) {
    esc_html_e( "Hello World, this is my first Dashboard Widget!", "textdomain" );
}

📄 原文内容

Adds a new dashboard widget.

Parameters

$widget_idstringrequired
Widget ID (used in the 'id' attribute for the widget).
$widget_namestringrequired
Title of the widget.
$callbackcallablerequired
Function that fills the widget with the desired content.
The function should echo its output.
$control_callbackcallableoptional
Function that outputs controls for the widget.

Default:null

$callback_argsarrayoptional
Data that should be set as the $args property of the widget array (which is the second parameter passed to your callback).

Default:null

$contextstringoptional
The context within the screen where the box should display.
Accepts 'normal', 'side', 'column3', or 'column4'. Default 'normal'.
$prioritystringoptional
The priority within the context where the box should show.
Accepts 'high', 'core', 'default', or 'low'. Default 'core'.

Source

function wp_add_dashboard_widget( $widget_id, $widget_name, $callback, $control_callback = null, $callback_args = null, $context = 'normal', $priority = 'core' ) {
	global $wp_dashboard_control_callbacks;

	$screen = get_current_screen();

	$private_callback_args = array( '__widget_basename' => $widget_name );

	if ( is_null( $callback_args ) ) {
		$callback_args = $private_callback_args;
	} elseif ( is_array( $callback_args ) ) {
		$callback_args = array_merge( $callback_args, $private_callback_args );
	}

	if ( $control_callback && is_callable( $control_callback ) && current_user_can( 'edit_dashboard' ) ) {
		$wp_dashboard_control_callbacks[ $widget_id ] = $control_callback;

		if ( isset( $_GET['edit'] ) && $widget_id === $_GET['edit'] ) {
			list($url)    = explode( '#', add_query_arg( 'edit', false ), 2 );
			$widget_name .= ' <span class="postbox-title-action"><a href="' . esc_url( $url ) . '">' . __( 'Cancel' ) . '</a></span>';
			$callback     = '_wp_dashboard_control_callback';
		} else {
			list($url)    = explode( '#', add_query_arg( 'edit', $widget_id ), 2 );
			$widget_name .= ' <span class="postbox-title-action"><a href="' . esc_url( "$url#$widget_id" ) . '" class="edit-box open-box">' . __( 'Configure' ) . '</a></span>';
		}
	}

	$side_widgets = array( 'dashboard_quick_press', 'dashboard_primary' );

	if ( in_array( $widget_id, $side_widgets, true ) ) {
		$context = 'side';
	}

	$high_priority_widgets = array( 'dashboard_browser_nag', 'dashboard_php_nag' );

	if ( in_array( $widget_id, $high_priority_widgets, true ) ) {
		$priority = 'high';
	}

	if ( empty( $context ) ) {
		$context = 'normal';
	}

	if ( empty( $priority ) ) {
		$priority = 'core';
	}

	add_meta_box( $widget_id, $widget_name, $callback, $screen, $context, $priority, $callback_args );
}

Changelog

Version Description
5.6.0 The $context and $priority parameters were added.
2.7.0 Introduced.

User Contributed Notes

  1. Skip to note 7 content

    Adding dashboard widgets
    Here is a simple dashboard widget:

    /**
     * Add a new dashboard widget.
     */
    function wpdocs_add_dashboard_widgets() {
    	wp_add_dashboard_widget( 'dashboard_widget', 'Example Dashboard Widget', 'dashboard_widget_function' );
    }
    add_action( 'wp_dashboard_setup', 'wpdocs_add_dashboard_widgets' );
    
    /**
     * Output the contents of the dashboard widget
     */
    function dashboard_widget_function( $post, $callback_args ) {
    	esc_html_e( "Hello World, this is my first Dashboard Widget!", "textdomain" );
    }

  2. Skip to note 9 content

    Adding widgets onto the side
    The function doesn’t allow you to choose where you want your widget to go and will automatically add it to the “core” which is the left side. However you are able to get it on the right side very easily.

    You can use the add_meta_box() function instead of wp_add_dashboard_widget. Simply specify ‘dashboard’ in place of the $post_type. For example:

    add_meta_box( 'id', 'Dashboard Widget Title', 'dash_widget', 'dashboard', 'side', 'high' );

  3. Skip to note 10 content


    Anonymous User



    The doc above states:

    $callback_args
    (array) (Optional) Data that should be set as the $args property of the widget array (which is the second parameter passed to your callback).
    Default value: null

    For anyone wondering what the first parameter of that call-back is, it is the current screen object.
    If used on the dashboard (which widgets will be), then that parameter returns an empty value.
    This is because the dashboard has no screen object.
    See also https://wordpress.org/support/topic/what-is-the-first-parameter-passed-to-wp_add_dashboard_widget-callback/

  4. Skip to note 11 content


    Anonymous User



    As noted in comment #714, wp_add_dashboard_widget() does not offer a great deal of flexibility to position a widget on the dashboard; however, it is possible to add a widget to a specific dashboard column relying on add_meta_box() and its $context parameter.

    The example below removes all core dashboard widgets and adds a custom one to the third dashboard column (tested ltr only). It looks odd, but it proves the point. 🙃

    https://developer.wordpress.org/reference/functions/add_meta_box/</a>
     */
    function wp_dashboard_setup() {
    
    	// Remove Welcome panel.
    	remove_action( 'welcome_panel', 'wp_welcome_panel' );
    
    	// Remove all Dashboard widgets.
    	global $wp_meta_boxes;
    	unset( $wp_meta_boxes['dashboard'] );
    
    	// Add custom dashbboard widget.
    	add_meta_box( 'dashboard_widget_example',
    		__( 'Example Widget', 'example-text-domain' ),
    		__NAMESPACE__ . 'render_example_widget',
    		'dashboard',
    		'column3',  // $context: 'advanced', 'normal', 'side', 'column3', 'column4'
    		'high',     // $priority: 'high', 'core', 'default', 'low'
    	);
    }
    
    /**
     * Render widget.
     */
    function render_example_widget() {
    ?>
    	<p>Do something.</p>
    </pre>
    				</div><!-- .comment-content -->
    
    					<section id='feedback-3537' class='wporg-has-embedded-code feedback hide-if-js' data-comment-count='0'>
    </section><!-- .feedback -->
    <footer class='feedback-links wporg-dot-link-list' >
    <a role="button" class="feedback-login" href="https://login.wordpress.org/?redirect_to=https%3A%2F%2Fdeveloper.wordpress.org%2Freference%2Ffunctions%2Fwp_add_dashboard_widget%2F%3Freplytocom%3D3537%23feedback-editor-3537" rel="nofollow">Log in to add feedback</a></footer>
    </article><!-- .comment-body -->
    </li>
    			<li id="comment-6217" data-comment-id="6217" class="comment byuser comment-author-nlpro odd alt thread-odd thread-alt depth-1">
    			<article id="div-comment-6217" class="comment-body">
    
    							<a href="#comment-content-6217" class="screen-reader-text">Skip to note 12 content</a>
    				<header class="comment-meta">
    					<div class="comment-author vcard">
    						<span class="comment-author-attribution">
    						<a href="https://profiles.wordpress.org/nlpro/" rel="external nofollow" class="url">nlpro</a>						</span>
    						<a class="comment-date" href="https://developer.wordpress.org/reference/functions/wp_add_dashboard_widget/#comment-6217">
    							<time datetime="2022-11-30T09:09:15+00:00">
    							3 years ago							</time>
    						</a>
    
    																													</div>
    					<div class="user-note-voting" data-nonce="ebf7ff5ae2" data-can-vote="false"><a class="user-note-voting-up" title="You must log in to vote on the helpfulness of this note" data-id="6217" data-vote="up" href="https://login.wordpress.org?redirect_to=https%3A%2F%2Fdeveloper.wordpress.org%2Freference%2Ffunctions%2Fwp_add_dashboard_widget%2F%23comment-6217"><span class="screen-reader-text">You must log in to vote on the helpfulness of this note</span></a><span class="user-note-voting-count " title=""><span class="screen-reader-text">Vote results for this note: </span>0</span><a class="user-note-voting-down" title="You must log in to vote on the helpfulness of this note" data-id="6217" data-vote="down" href="https://login.wordpress.org?redirect_to=https%3A%2F%2Fdeveloper.wordpress.org%2Freference%2Ffunctions%2Fwp_add_dashboard_widget%2F%23comment-6217"><span class="screen-reader-text">You must log in to vote on the helpfulness of this note</span></a></div>				</header>
    				<!-- .comment-metadata -->
    			
    				<div class="wporg-has-embedded-code comment-content" id="comment-content-6217">
    				<p>Note that if a plugin implements i18n (internationalization/translation) the $widget_name parameter value needs to be passed to the function using a translation function. Example:</p>
    <pre class="wp-block-code"><code lang="php" class="language-php ">wp_add_dashboard_widget( $widget_id, __( 'This is a translated widget title', 'example-plugin' ), … );