将屏幕选项添加到自定义管理页面


13

我想将屏幕选项添加到我的插件设置页面,例如仪表板中可用的选项。

在此处输入图片说明

我尝试使用对象的add_option方法,WP_Screen发现它仅支持两个选项。per_pagelayout_columns

有谁知道要使用哪个屏幕选项来获得“仪表板”页面中的选项?

编辑

让我解释一下我要尝试的内容。

我的批量删除插件中有不同的部分,每个部分让人们根据一些条件(例如类别,标签,自定义分类法等)删除帖子。我想让用户选择要使用的部分以及要隐藏的部分,类似于“仪表板”页面,用户可以在其中选择要查看的仪表板小部件以及要隐藏的仪表板小部件。

现在,要实现此目的,我想显示一个复选框列表(每个部分一个),然后让用户选择要显示的复选框。

为了显示复选框列表,我必须调用对象的add_option方法WP_Screen。当我这样做时,我发现当前add_option函数仅支持这两种类型,而其他函数则被忽略。

  • 每页
  • layout_columns

但是,仅在仪表板页面中会显示复选框。我想知道如何在自定义管理页面的屏幕选项部分中复制类似的内容。


是的,“屏幕选项”选项卡似乎无懈可击...劫持“帮助”选项卡怎么办?
brasofilo

Answers:


6

您无需发明新的屏幕选项行。只需使用适当的元框即可。

当前,您正在绘制伪元框:

<!-- Post status start-->
        <div class = "postbox">
            <div class = "handlediv"> <br> </div>
            <h3 class = "hndle"><span><?php _e("By Post Status", 'bulk-delete'); ?></span></h3>
        <div class = "inside">
        <h4><?php _e("Select the posts which you want to delete", 'bulk-delete'); ?></h4>

你应该做这个:

<div id="post-body-content">
    <!-- #post-body-content -->
</div>

<div id="postbox-container-1" class="postbox-container">
    <?php do_meta_boxes('','side',$object); ?>
</div>

<div id="postbox-container-2" class="postbox-container">
    <?php do_meta_boxes('','normal',$object); ?>
    <?php do_meta_boxes('','advanced',$object); ?>
</div>

然后使用来注册自己的metabox add_meta_box()

阅读关于自定义页面的Meta盒斯蒂芬·哈里斯的所有细节(演示GitHub上)。
要点是:您将免费获得这些框的屏幕选项。

而且,当WordPress一天更改元框的内部标记时,您的代码可能仍然可以工作,因为您已经使用了API。


感谢您提供的代码和链接。修改我的插件以现在将其合并。
Sudar 2013年

4

您可以通过在\WP_Screen类中使用适当的过滤器来做到这一点。只要确保您没有默认将其打开即可

如何显示或隐藏标签

以下过滤器显示了如何显示或隐藏选项卡。实际上,由于有了更好的过滤器,如果需要在选项卡已经存在时强制隐藏它,则以下方法会更有用:

add_filter( 'screen_options_show_screen', function( $show, \WP_Screen $screen )
{
    // Navigate to the screen of choice and uncomment the following line to find out the 'base' val
    // var_dump( $screen );
    return 'your_screen_id' !== $screen->base
        ? $show
        : true;
}, 10, 2 );

如何显示标签和添加自定义内容

下面显示了一个设置选项卡,其中包含一个输入字段,其中包含amount您可以在页面上以任何方式使用的值(例如,限制$wpdb查询结果)。

/**
 * @param string     $settings
 * @param \WP_Screen $screen
 */
add_filter( 'screen_settings', function( $settings, \WP_Screen $screen )
{
    if ( 'your_screen_id' !== $screen->base )
        return $settings;

    $amount = isset( $_GET['paged'] ) 
        ? filter_var(
            absint( $_GET['paged'] ),
            FILTER_SANITIZE_NUMBER_INT,
            FILTER_NULL_ON_FAILURE
        ) 
        : 1;

    return sprintf(
        '<label for="amount">Amount:</label> '
        .'<input step="1" min="1" max="999" class="screen-per-page" name="amount" val="%d">',
        .get_submit_button( 'Set', 'secondary', 'submit-amount', false ),
        $amount
    );
}, 10, 2 );

1

这是一个完整而简洁的示例,该示例基于Stephen Harris的“自定义页面上的元框”

要旨相同的代码

<?php

/**
 * Plugin Name:     LHF Volunteer Form
 * Description:     Manages a google-sheet full of names and emails
 * Plugin URI:      http://ladehammerfestivalen.no/volunteer
 * Author URI:      http://genja.org
 * Author:          jazzoslav@gmail.com
 * Text Domain:     lhf-volunteer-form
 * Domain Path:     /languages
 * Version:         0.2.0
 * @package         Lhf_Volunteer_Form
 */

require_once  __DIR__ . '/vendor/autoload.php';

use Lhf\Sheet\RegistrationsSheet;

frivilligSystemMain();

function frivilligSystemMain() {
    try {
        $regSheet = \Lhf\Sheet\RegistrationsSheet::createInWordPress();
    } catch (\Exception $ex) {
        error_log(sprintf('%s:%d %s', __FILE__, __LINE__, $ex->getMessage()));
    }
    add_action('init', function() use ($regSheet) {
        if (is_admin()) {
            add_action( 'admin_menu', function() use ($regSheet) {
                $screenId = DashboardView::screen_id;
                $pageId = add_dashboard_page( 'hammerater', 'Hammerater', 'endre_frivillig_skjema', $screenId,
                    function () use ($regSheet) { DashboardView::renderVolunteerDashboard($regSheet); } );
                add_action("load-$pageId", function() use ($regSheet, $pageId, $screenId) {
                    wp_enqueue_script('postbox');
                    add_screen_option('layout_columns', array('max' => 2, 'default' => 2) );
                    do_action("add_meta_boxes_$screenId", null); // allow third parties to hook into this.
                    do_action('add_meta_boxes', $screenId, null); // allow third parties to hook into this.
                });
                add_action("add_meta_boxes_$screenId", function () use ($regSheet) { DashboardView::registerMetaboxes($regSheet); });
            });
        }
    });
}

class DashboardView
{
    const screen_id = 'frivillig-liste';

    private static function includeAdminHeader()
    {
        require_once( ABSPATH . 'wp-admin/admin.php');
        require_once( ABSPATH . 'wp-admin/includes/dashboard.php');
        require_once( ABSPATH . 'wp-admin/admin-header.php');
        wp_dashboard_setup();
        wp_enqueue_script( 'dashboard' );
        add_thickbox();
        do_action( 'add_meta_boxes' );
        if ( wp_is_mobile() ) {
            wp_enqueue_script( 'jquery-touch-punch' );
            //wp_dequeue_script('jquery-migrate');
        }

        wp_enqueue_script( 'datatables', '//cdn.datatables.net/1.10.16/js/jquery.dataTables.js');
        wp_enqueue_style( 'datatables', '//cdn.datatables.net/1.10.16/css/jquery.dataTables.css');

        wp_enqueue_script( 'datatables-responsive', '//cdn.datatables.net/responsive/2.2.1/js/dataTables.responsive.min.js');
        wp_enqueue_style(  'datatables-responsive', '//cdn.datatables.net/responsive/2.2.1/css/responsive.dataTables.min.css');

        wp_enqueue_script( 'datatables-row-group', '//cdn.datatables.net/rowgroup/1.0.2/js/dataTables.rowGroup.min.js');
        wp_enqueue_style(  'datatables-row-group', '//cdn.datatables.net/rowgroup/1.0.2/css/rowGroup.dataTables.min.css');
    }

    static function renderVolunteerDashboard(RegistrationsSheet $regSheet) {
        static::includeAdminHeader();
        wp_enqueue_script('lhf-sheets');
        $workTypes = get_option( 'lhfsheets_form_work_types' );
        ?>
        <div class="wrap">
            <form>
<?php
        wp_nonce_field( 'meta-box-order', 'meta-box-order-nonce', false );
        wp_nonce_field( 'closedpostboxes', 'closedpostboxesnonce', false );
?>
            <h1>Frivillige Hammerater</h1>
            <h2 class="nav-tab-wrapper">
                <a href="<?= admin_url( 'index.php?page=frivillig-liste&tab=liste' ) ?>" >Liste</a>
                <a href="<?= admin_url( 'index.php?page=frivillig-liste&tab=preferanser' ) ?>">Arbeidsposter</a>
                <a href="<?= admin_url( 'index.php?page=frivillig-liste&tab=info' ) ?>">Frivilliginfo</a>
            </h2>
            <?php
            $screen      = get_current_screen();
            $columns     = absint( $screen->get_columns() );
            $columns_css = '';
            if ( $columns ) {
                $columns_css = " columns-$columns";
            }
            ?>

            <?php if ( $_GET['tab'] == 'liste' || ! $_GET['tab'] ) { ?>
                <div id="dashboard-widgets" class="metabox-holder<?php echo $columns_css; ?>">
                    <div id="postbox-container-1" class="postbox-container">
                        <?php do_meta_boxes( $screen->id, 'main_list', '' ); ?>
                    </div>
                </div>
            <?php } ?>

            <?php if ( $_GET['tab'] == 'preferanser' || ! $_GET['tab'] ) { ?>
                <div id="dashboard-widgets" class="metabox-holder<?php echo $columns_css; ?>">
                    <div id="preferences-sortables" class="postbox-container">
                        <?php do_meta_boxes( $screen->id, 'preferences', ''); ?>
                    </div>
                    <div id="preferences_left-sortables" class="postbox-container">
                        <?php do_meta_boxes( $screen->id, 'preferences_right', ''); ?>
                    </div>
                </div>
            <?php } ?>
            <?php if ( $_GET['tab'] == 'info' ) { ?>
                        <h3>Annen info</h3>
            <?php } ?>
            </form>
        </div>
        <?php
    }

    static function renderMainList($records, $status = 'registered/served/contacted') {
        /** @var Frivillig $e */
        ?>
        <div class="main">
          <table id="frivillige-hammerater-<?= $status ?>" style="display:none" data-status="<?= $status ?>">
            <?php foreach ($records as $e) { ?>
              <tr> ...  </tr>
            <?php } ?>
            </tbody>
          </table>
        </div>
        <?php
    }

    public static function registerMetaboxes( RegistrationsSheet $regSheet ) {
        if ($_GET['tab'] == 'info') { return; }
        $all = $regSheet->getVolunteerRecords();
        if ($_GET['tab'] == 'liste' || $_GET['tab'] === null) {
            foreach (Frivillig::states() as $state) {
                add_meta_box(
                    "volunteers-search-all",
                    __('Verktøy') ,
                    function () use ($state) { DashboardView::renderGlobalSearchMetaBox(); },
                    'dashboard_page_frivillig-liste',
                    'main_list'
                );

                $peopleWithState = [];
                foreach ($all as $f) { if ($f->status === $state) { $peopleWithState[] = $f; } }

                add_meta_box(
                    "volunteers-$state",
                    DashboardView::$stateName[$state],
                    function () use ($peopleWithState, $state) { DashboardView::renderMainList($peopleWithState, $state); },
                    'dashboard_page_frivillig-liste',
                    'main_list'
                );
            }
        }

        if ($_GET['tab'] == 'preferanser') {
            $workTypes = get_option('lhfsheets_form_work_types');
            foreach ($workTypes as $workType) {
                $workers = [];
                foreach ($all as $frivillig) {
                    $interests = preg_split('/,\s+/', $frivillig->interests);
                    if (in_array($workType['slug'], $interests)) {
                        $workers[] = $frivillig;
                    }
                }
                add_meta_box(
                    "volunteer-prefers-{$workType['slug']}",
                    $workType['description'],
                    function () use ($workers, $workType) { DashboardView::renderPreferences($workers, $workType); },
                    'dashboard_page_frivillig-liste',
                    'preferences'
                );
            }
        }
    }

    public static function renderPreferences($workers, $workType) { ?>
        <ul>
            <?php foreach ($workers as $e) { ?>
            <li data-id="<?= $e->id ?>"> ...  </li>
            <?php } ?>
        </ul>
        <?php
    }

    private static function renderGlobalSearchMetaBox() {
        ?> Søk: <input type="text" onkeydown="window.populateSearchFields(event)" placeholder="<?= __('i alle tabellene') ?>  "> <?php
    }
}

参考资料

https://codex.wordpress.org/Dashboard_Widgets_API

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.