WP_list_table prepare_items()

时间:2016-03-15 作者:normala

我创建了自定义的WP\\U list\\U表格,附带了类似的表单(添加新的类别表单),但当我提交表单时,WP\\U list\\U表格不会刷新。当我再次刷新页面时,会显示信息。我使用wp\\u list\\u table\\u example插件,除了获取example\\u数据和表单之外,其他一切都是一样的。

 class TT_Example_List_Table extends WP_List_Table {

    function __construct(){
        global $status, $page;

        //Set parent defaults
        parent::__construct( array(
            \'singular\'  => \'movie\',     //singular name of the listed records
            \'plural\'    => \'movies\',    //plural name of the listed records
            \'ajax\'      => false        //does this table support ajax?
        ) );

    }
    function column_default($item, $column_name){
        switch($column_name){
            case \'rating\':
            case \'director\':
                return $item[$column_name];
            default:
                return print_r($item,true); //Show the whole array for troubleshooting purposes
        }
    }

    function column_title($item){

        //Build row actions
        $actions = array(
            \'edit\'      => sprintf(\'<a href="?page=%s&action=%s&movie=%s">Edit</a>\',$_REQUEST[\'page\'],\'edit\',$item[\'ID\']),
            \'delete\'    => sprintf(\'<a href="?page=%s&action=%s&movie=%s">Delete</a>\',$_REQUEST[\'page\'],\'delete\',$item[\'ID\']),
        );

        //Return the title contents
        return sprintf(\'%1$s <span style="color:silver">(id:%2$s)</span>%3$s\',
            /*$1%s*/ $item[\'title\'],
            /*$2%s*/ $item[\'ID\'],
            /*$3%s*/ $this->row_actions($actions)
        );
    }
    function column_cb($item){
        return sprintf(
            \'<input type="checkbox" name="%1$s[]" value="%2$s" />\',
            /*$1%s*/ $this->_args[\'singular\'],  //Let\'s simply repurpose the table\'s singular label ("movie")
            /*$2%s*/ $item[\'ID\']                //The value of the checkbox should be the record\'s id
        );
    }

    function get_columns(){
        $columns = array(
            \'cb\'        => \'<input type="checkbox" />\', //Render a checkbox instead of text
            \'title\'     => \'Title\',
            \'rating\'    => \'Rating\',
        );
        return $columns;
    }

    function get_sortable_columns() {
        $sortable_columns = array(
            \'title\'     => array(\'title\',false),     //true means it\'s already sorted
            \'rating\'    => array(\'rating\',false),
            \'director\'  => array(\'director\',false)
        );
        return $sortable_columns;
    }

    function get_bulk_actions() {
        $actions = array(
            \'delete\'    => \'Delete\'
        );
        return $actions;
    }
    function process_bulk_action() {

        //Detect when a bulk action is being triggered...
        if( \'delete\'===$this->current_action() ) {
            wp_die(\'Items deleted (or they would be if we had items to delete)!\');
        }

    }
    function prepare_items() {


          $data = array();
        $example_data = array();
    $terms = get_terms( \'productcat\', array(\'hide_empty\' => false));

print_r($terms);
        if ( ! empty( $terms )  ){
     foreach ( $terms as $term ) {

         $data[] = array(
                            \'ID\'          =>  $term->term_id,
                            \'title\'       => $term->name
                            );

     }
 }

        $example_data = $data;

        $per_page = 5;


        $columns = $this->get_columns();
        $hidden = array();
        $sortable = $this->get_sortable_columns();
        $this->_column_headers = array($columns, $hidden, $sortable);
        $this->process_bulk_action();
        $data = $example_data;

        function usort_reorder($a,$b){
            $orderby = (!empty($_REQUEST[\'orderby\'])) ? $_REQUEST[\'orderby\'] : \'title\'; //If no sort, default to title
            $order = (!empty($_REQUEST[\'order\'])) ? $_REQUEST[\'order\'] : \'asc\'; //If no order, default to asc
            $result = strcmp($a[$orderby], $b[$orderby]); //Determine sort order
            return ($order===\'asc\') ? $result : -$result; //Send final sort direction to usort
        }
        usort($data, \'usort_reorder\');

        $current_page = $this->get_pagenum();
        $total_items = count($data);
        $data = array_slice($data,(($current_page-1)*$per_page),$per_page);

        $this->items = $data;


        $this->set_pagination_args( array(
            \'total_items\' => $total_items,                  //WE have to calculate the total number of items
            \'per_page\'    => $per_page,                     //WE have to determine how many items to show on a page
            \'total_pages\' => ceil($total_items/$per_page)   //WE have to calculate the total number of pages
        ) );
    }


}


function tt_add_menu_items(){
    add_menu_page(\'Example Plugin List Table\', \'List Table Example\', \'activate_plugins\', \'tt_list_test\', \'tt_render_list_page\');
} add_action(\'admin_menu\', \'tt_add_menu_items\');


function tt_render_list_page(){

    //Create an instance of our package class...
    $testListTable = new TT_Example_List_Table();
    //Fetch, prepare, sort, and filter our data...
    $testListTable->prepare_items();




    ?>
    <div class="wrap">

        <div id="icon-users" class="icon32"><br/></div>
        <h2>List Table Test</h2>

        <form id="movies-filter" method="GET">

            <!-- For plugins, we also need to ensure that the form posts back to our current page -->
            <input type="hidden" name="page" value="<?php echo $_REQUEST[\'page\'] ?>" />
            <!-- Now we can render the completed list table -->
            <?php $testListTable->display(); ?>

        </form>
          <form id="insert_term" name="insert_term" method="post" action=""> 

           <div class="form-field  term-name-wrap">
          <label for="term">Term</label>
         <input type="text" value="" name="term" id="term" size="40" />
         <p>Description</p>
        </div>

    <label>Description</label><input type="text" value="" name="termdesc" id="termdesc" />

    <input type="submit" value="Add term" id="submit" name="submit" />
    <input type="hidden" name="action" value="new_term" />

</form> 

         <?php

if( \'POST\' == $_SERVER[\'REQUEST_METHOD\']) &&  $_POST[\'action\'] == "new_term") {
if (isset($_POST[\'term\']) && !empty( $_POST[\'term\']) ) {

 $new_term =  $_POST[\'term\'];
 $description = $_POST[\'desc\'];
        wp_insert_term(
          $new_term,
          \'productcat\',
            array(
         \'description\'=> $description,
        ));

    } 

}

?>        
    </div>
    <?php
}
我的问题是,当我在表单中添加新术语时,为什么不刷新wp\\u list\\u表,这是因为获取数据的方式还是因为添加数据的方式。提交新学期后如何刷新wp\\u table\\u列表。欢迎任何帮助。

1 个回复
SO网友:Kumar

在已经显示了表列表之后,您正在处理新术语,因此为了显示新术语,在提交表单后,您需要在显示表之前对其进行处理。

我添加了一个新函数process_form() 在这里,它处理新表单提交的处理,因此在提交表单时,它将验证nonce字段(您应该始终使用该字段wp_create_nonce_field() ) 并添加一个术语。

此外,对于页面标题,您不再需要icon32 div<div id="icon-users" class="icon32"><br/></div>, 你应该移除这个。

页面标题需要包含在<h1> WordPress 4.3之后的管理员屏幕标签:https://make.wordpress.org/core/2015/07/31/headings-in-admin-screens-change-in-wordpress-4-3/

function tt_render_list_page() {
    //Handle New Term Form Submission
    $this->wpse_220820_process_form();
    //Create an instance of our package class...
    $testListTable = new TT_Example_List_Table();
    //Fetch, prepare, sort, and filter our data...
    $testListTable->prepare_items(); ?>
    <div class="wrap">

        <div id="icon-users" class="icon32"><br/></div>
        <h1>List Table Test</h1>

        <form id="movies-filter" method="GET">

            <!-- For plugins, we also need to ensure that the form posts back to our current page -->
            <input type="hidden" name="page" value="<?php echo $_REQUEST[\'page\'] ?>"/>
            <!-- Now we can render the completed list table -->
            <?php $testListTable->display(); ?>

        </form>
        <form id="insert_term" name="insert_term" method="post" action="">

            <div class="form-field  term-name-wrap">
                <label for="term">Term</label>
                <input type="text" value="" name="term" id="term" size="40"/>
                <p>Description</p>
            </div>

            <label>Description</label><input type="text" value="" name="termdesc" id="termdesc"/>

            <input type="submit" value="Add term" id="submit" name="submit"/>
            <input type="hidden" name="action" value="new_term"/>
            <?php wp_nonce_field( \'wpse_220788_new_term\', \'new_term_nonce\' ); ?>
        </form>
    </div>
    <?php
}

/**
 * Checks $_POST for Form submission and insert it into table
 */
function wpse_220820_process_form() {
    if ( ! empty( $_POST[\'action\'] ) && $_POST[\'action\'] == "new_term" ) {
        //Verify Nonce
        if ( ! empty( $_POST[\'new_term_nonce\'] ) && wp_verify_nonce( $_POST[\'new_term_nonce\'], \'wpse_220788_new_term\' ) ) {
            if ( isset( $_POST[\'term\'] ) && ! empty( $_POST[\'term\'] ) ) {

                $new_term    = sanitize_text_field( $_POST[\'term\'] );
                $description = sanitize_text_field( $_POST[\'desc\'] );
                wp_insert_term(
                    $new_term,
                    \'productcat\',
                    array(
                        \'description\' => $description,
                    )
                );

            }
        }

    }
}

相关推荐

在管理员帖子wp-list-table之前/之后添加内容

我知道有两个钩子可以在分类法wp列表前后添加内容。是否有操作可在编辑上的post type wp list表格后添加内容。php页面?$taxonomy列表:add_action( \'category\' . \'_pre_add_form\', \'copy_above_form\' ); function copy_above_form( $taxonomy ) { echo \'<p>Above the WP-List-Table</p>\';&#x