使用wp_add_dashboard_widget()函数添加WordPress仪表板小工具

在WordPress 2.7版中添加了Dashboard Widgets API,可以轻松地向管理仪表板添加新的窗口小部件  。

这部分需要具备PHP和WordPress 插件API的相关知识  ,但是对于熟悉钩子操作和过滤器的插件或主题作者来说,这只需要几分钟,这是使您的插件更加有用的好方法。

使用wp_add_dashboard_widget()函数添加WordPress仪表板小工具

默认仪表板小工具

概述

主要功能

添加仪表板小部件所需的主要工具是  wp_add_dashboard_widget()  函数。您可以在该链接上找到此函数的完整说明,但是下面给出了简要概述。

用法

wp_add_dashboard_widget( $widget_id, $widget_name, $callback, $control_callback, $callback_args );
  • $widget_id:您的小部件的识别号。这将用作其CSS类以及其在小部件数组中的键。
  • $widget_name:这是小部件将在其标题中显示的名称。
  • $callback:您将创建的函数的名称,该函数将显示小部件的实际内容。
  • $control_callback (可选):您创建的函数的名称,该函数将处理小部件选项表单的提交,并且还将显示表单元素。
  • $callback_args (可选):回调函数的参数集。

动作钩子

要运行该函数,您将需要通过  add_action()挂接到动作  wp_dashboard_setup。对于多站点中的网络管理仪表板,请使用多站点版本钩子  wp_network_dashboard_setup

/**
 * Add a widget to the dashboard.
 *
 * This function is hooked into the 'wp_dashboard_setup' action below.
 */
function wporg_add_dashboard_widgets() {
    // Add function here
}
add_action( 'wp_dashboard_setup', 'wporg_add_dashboard_widgets' );

网络仪表板:

/**
 * Add a widget to the network dashboard.
 *
 * This function is hooked into the 'wp_network_dashboard_setup' action below.
 */
function wporg_add_network_dashboard_widgets() {
    // Add function here
}
add_action( 'wp_network_dashboard_setup', 'wporg_add_network_dashboard_widgets' );

范例

基本用法

/**
 * Add a widget to the dashboard.
 *
 * This function is hooked into the 'wp_dashboard_setup' action below.
 */
function wporg_add_dashboard_widgets() {
    wp_add_dashboard_widget(
        'wporg_dashboard_widget',                          // Widget slug.
        esc_html__( 'Example Dashboard Widget', 'wporg' ), // Title.
        'wporg_dashboard_widget_render'                    // Display function.
    ); 
}
add_action( 'wp_dashboard_setup', 'wporg_add_dashboard_widgets' );
 
/**
 * Create the function to output the content of our Dashboard Widget.
 */
function wporg_dashboard_widget_render() {
    // Display whatever you want to show.
    esc_html_e( "Howdy! I'm a great Dashboard Widget.", "wporg" );
}

强制小工具顶端

通常,您只需将插件的用户拖动到周围,就可以将其Dashboard Widget放置在所需的位置。当前没有一种简单的API方式可以对默认窗口小部件进行预排序,这意味着您的新窗口小部件将始终位于列表的底部。在将排序添加到API之前,解决此问题有点复杂。

下面是一个示例挂钩函数,它将尝试将您的窗口小部件放在默认窗口小部件之前。为此,您可以手动更改元框的内部数组(其中的仪表板小部件是一种),然后将其放在列表的顶部,使其首先显示。

function wporg_add_dashboard_widgets() {
    wp_add_dashboard_widget( 
        'wporg_dashboard_widget', 
        esc_html__( 'Example Dashboard Widget', 'wporg' ), 
        'wporg_dashboard_widget_function'
    );
     
    // Globalize the metaboxes array, this holds all the widgets for wp-admin.
    global $wp_meta_boxes;
     
    // Get the regular dashboard widgets array 
    // (which already has our new widget but appended at the end).
    $default_dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
     
    // Backup and delete our new dashboard widget from the end of the array.
    $example_widget_backup = array( 'example_dashboard_widget' => $default_dashboard['example_dashboard_widget'] );
    unset( $default_dashboard['example_dashboard_widget'] );
  
    // Merge the two arrays together so our widget is at the beginning.
    $sorted_dashboard = array_merge( $example_widget_backup, $default_dashboard );
  
    // Save the sorted array back into the original metaboxes. 
    $wp_meta_boxes['dashboard']['normal']['core'] = $sorted_dashboard;
}
add_action( 'wp_dashboard_setup', 'wporg_add_dashboard_widgets' );

不幸的是,这仅适用于从未重新排序其小部件的人。用户完成操作后,其现有偏好将覆盖此设置,因此他们必须将您的窗口小部件移至顶部,以使其停留在那里。

删除默认的仪表板小工具

在某些情况下,尤其是在多用户博客上,从界面中完全删除窗口小部件可能会很有用。默认情况下,每个用户都可以使用 顶部的“ 屏幕选项”选项卡关闭任何给定的窗口小部件  ,但是如果您有很多非技术用户,那么他们根本看不到它可能会更好。

要删除仪表板小部件,请使用  remove_meta_box()  函数。有关所需参数,请参见下面的示例代码。

这些是仪表板上默认窗口小部件的名称:

// Main column (left): 
// Browser Update Required
$wp_meta_boxes['dashboard']['normal']['high']['dashboard_browser_nag']; 
// PHP Update Required
$wp_meta_boxes['dashboard']['normal']['high']['dashboard_php_nag']; 
 
// At a Glance
$wp_meta_boxes['dashboard']['normal']['core']['dashboard_right_now'];
// Right Now
$wp_meta_boxes['dashboard']['normal']['core']['network_dashboard_right_now'];
// Activity
$wp_meta_boxes['dashboard']['normal']['core']['dashboard_activity'];
// Site Health Status
$wp_meta_boxes['dashboard']['normal']['core']['health_check_status'];
 
// Side Column (right): 
// WordPress Events and News
$wp_meta_boxes['dashboard']['side']['core']['dashboard_primary'];
// Quick Draft, Your Recent Drafts
$wp_meta_boxes['dashboard']['side']['core']['dashboard_quick_press'];

这是删除QuickPress小部件的示例函数:

// Create the function to use in the action hook
function wporg_remove_dashboard_widget() {
    remove_meta_box( 'dashboard_quick_press', 'dashboard', 'side' );
} 
// Hook into the 'wp_dashboard_setup' action to register our function
add_action( 'wp_dashboard_setup', 'wporg_remove_dashboard_widget' );

下面的示例删除了所有仪表板小部件:

function wporg_remove_all_dashboard_metaboxes() {
    // Remove Welcome panel
    remove_action( 'welcome_panel', 'wp_welcome_panel' );
    // Remove the rest of the dashboard widgets
    remove_meta_box( 'dashboard_primary', 'dashboard', 'side' );
    remove_meta_box( 'dashboard_quick_press', 'dashboard', 'side' );
    remove_meta_box( 'health_check_status', 'dashboard', 'normal' );
    remove_meta_box( 'dashboard_right_now', 'dashboard', 'normal' );
    remove_meta_box( 'dashboard_activity', 'dashboard', 'normal');
}
add_action( 'wp_dashboard_setup', 'wporg_remove_all_dashboard_metaboxes' );

在右侧添加小部件

该功能不允许您选择要放置小部件的位置,并且会自动将其添加到左侧的“核心”中。但是,您可以很容易地在右侧获得它。

您可以使用  add_meta_box()  函数代替  wp_add_dashboard_widget。只需在$post_type位置指定“ dashboard”即可。例如:

add_meta_box( 
    'dashboard_widget_id', 
    esc_html__( 'Dashboard Widget Title', 'wporg' ), 
    'dashboard_widget', 
    'dashboard', 
    'side', 'high'
);

或者,在创建小部件之后:

function wporg_add_dashboard_widget() {
    wp_add_dashboard_widget( 
        'wporg_dashboard_widget', 
        esc_html__( 'Example Dashboard Widget', 'wporg' ), 
        'wporg_dashboard_widget_function'
    );
     
    // Global the $wp_meta_boxes variable (this will allow us to alter the array).
    global $wp_meta_boxes;
 
    // Then we make a backup of your widget.
    $wporg_widget = $wp_meta_boxes['dashboard']['normal']['core']['wporg_dashboard_widget'];
 
    // We then unset that part of the array.
    unset( $wp_meta_boxes['dashboard']['normal']['core']['wporg_dashboard_widget'] );
 
    // Now we just add your widget back in.
    $wp_meta_boxes['dashboard']['side']['core']['wporg_dashboard_widget'] = $wporg_widget;
}
add_action( 'wp_dashboard_setup', 'wporg_add_dashboard_widget' );

在仪表板中汇聚RSS资讯

如果您需要在小部件中聚合RSS,则应查看使用缓存设置现有插件的方式  /wp-admin/includes/dashboard.php

窗口小部件选项

WordPress没有提供一种内置的方式来获取特定小部件的选项。默认情况下,您将需要使用  get_option( 'dashboard_widget_options' ) 获取所有窗口小部件选项,然后手动过滤返回的数组。本节介绍可以轻松添加到主题或插件中的一些功能,以帮助获取和设置窗口小部件选项。

获取小工具选项

此函数将获取所有窗口小部件选项,或仅获取指定窗口小部件的选项:

/**
 * Gets all widget options, or only options for a specified widget if a widget id is provided.
 *
 * @param string $widget_id Optional. If provided, will only get options for that widget.
 * @return array An associative array
 */
function wporg_get_dashboard_widget_options( $widget_id = '' ) {
    // Fetch ALL dashboard widget options from the db
    $options = get_option( 'dashboard_widget_options' );
  
    // If no widget is specified, return everything
    if ( empty( $widget_id ) ) {
        return $options;
    }
  
    // If we request a widget and it exists, return it
    if ( isset( $options[$widget_id] ) ) {
        return $options[$widget_id];
    }
  
    // Something went wrong...
    return false;
}

寻找单个小工具选项

如果您只想轻松获取单个选项(用于输出到主题),则以下函数将使此操作变得更容易。该示例应与前面的“ 获取窗口小部件选项”示例函数一起使用。

/**
 * Gets one specific option for the specified widget.
 * 
 * @param  string $widget_id Widget ID.
 * @param  string $option    Widget option.
 * @param  string $default   Default option.
 * 
 * @return string            Returns single widget option.
 */
function wporg_get_dashboard_widget_option( $widget_id, $option, $default = NULL ) {
    $options = wporg_get_dashboard_widget_options( $widget_id );
 
    // If widget options don't exist, return false.
    if ( ! $options ) {
        return false;
    }
 
    // Otherwise fetch the option or use default
    if ( isset( $options[$option] ) && ! empty( $options[$option] ) ) {
        return $options[$option];
    } else {
        return ( isset( $default ) ) ? $default : false;
    }
}

更新小工具选项

此功能可用于轻松更新小部件的所有选项。它还可以用于非破坏性地添加窗口小部件选项。只需将$add_option参数设置为true,就不会覆盖任何现有选项(尽管它将添加所有缺少的选项)。

/**
 * Saves an array of options for a single dashboard widget to the database.
 * Can also be used to define default values for a widget.
 *
 * @param string $widget_id  The name of the widget being updated
 * @param array $args        An associative array of options being saved.
 * @param bool $add_only     Set to true if you don't want to override any existing options.
 */
function update_dashboard_widget_options( $widget_id , $args = array(), $add_only = false ) {
    // Fetch ALL dashboard widget options from the db...
    $options = get_option( 'dashboard_widget_options' );
 
    // Get just our widget's options, or set empty array.
    $widget_options = ( isset( $options[$widget_id] ) ) ? $options[$widget_id] : array();
 
    if ( $add_only ) {
        // Flesh out any missing options (existing ones overwrite new ones).
        $options[$widget_id] = array_merge( $args, $widget_options );
    } else {
        // Merge new options with existing ones, and add it back to the widgets array.
        $options[$widget_id] = array_merge( $widget_options, $args );
    }
 
    // Save the entire widgets array back to the db.
    return update_option( 'dashboard_widget_options', $options );
}

有关更多示例,请参见示例仪表板小部件

 

 

发表评论