WordPress函数:wp_add_dashboard_widget 添加仪表板小部件

江河/ 2023年11月06日/ WordPress/ 浏览 914

函数原型:


wp_add_dashboard_widget( string $widget_id, string $widget_name, callable $callback, callable $control_callback = null, array $callback_args = null, string $context = 'normal', string $priority = 'core' )


添加一个新的仪表板小部件


参数说明:


$widget_id 小部件ID(用于小部件的“ID”属性)。


$widget_name 小部件的标题。


$callback 回调函数,用所需内容填充小部件。函数应回显其输出。


$control_callback 为小部件输出控件的函数。默认值:null


$callback_args 应设置为小部件数组的$args属性的数据(这是传递给回调的第二个参数)。默认值:null


$context 应显示的屏幕中的上下文。接受“normal”、“side”、“column3”或“column4”。默认为“正常”。默认值:“normal”


$priority 应显示的上下文中的优先级。接受“high”、“core”、“default”或“low”。默认“core”。默认值:“core”


函数源码:


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 );
}


使用举例:


/**
 * 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" );
}


发表评论

暂无评论,抢个沙发...

客服 工单