Таблица администрирования Wordpress - сортировка столбцов не работает в результатах поиска - PullRequest
0 голосов
/ 20 февраля 2019

Я хочу отображать таблицы собственных администраторов на странице подменю, это то, что я смог сделать.

Поиск также возможен, но есть проблема, я также хочу использовать сортируемые столбцы.Однако, если я отсортирую по столбцу в результатах поиска, все записи будут отображаться вместо сортировки там.

Я действительно понятия не имею, в чем проблема.Здесь, в Stackoverflow, я ничего не нашел, точно так же, как я ничего не нашел в Google.

Я был бы очень рад, если бы здесь можно было найти кого-то, кто знаком с этой темой и, возможно, сможет мне помочь.Я очень благодарен за все советы и подсказки.

<?php

        if (!class_exists('WP_List_Table'))
            {
            require_once ('../../assets/lib/class-wp-list-table.php');

            }

        class My_List_Table extends WP_List_Table

            {
            public

            function no_items()
                {
                _e('Unfortunately there are no ingredients available :(', 'wp-my-recipe');
                }

            /**
             * Prepare the items for the table to process
             *
             * @return Void
             */
            public

            function prepare_items($search = NULL)
                {
                $data = $this->table_data($search);
                $columns = $this->get_columns();
                $hidden = $this->get_hidden_columns();
                $sortable = $this->get_sortable_columns();
                $perPage = 1;
                $currentPage = $this->get_pagenum();
                if (!is_null($data))
                    {
                    $totalItems = count($data);
                    $data = array_slice($data, (($currentPage - 1) * $perPage) , $perPage);
                    }
                  else
                    {
                    $totalItems = 0;
                    }

                $this->set_pagination_args(array(
                    'total_items' => $totalItems,
                    'per_page' => $perPage
                ));
                $this->_column_headers = array(
                    $columns,
                    $hidden,
                    $sortable
                );
                $this->items = $this->table_data($search);
                }

            /**
             * Override the parent columns method. Defines the columns to use in your listing table
             *
             * @return Array
             */
            public

            function get_columns()
                {
                $columns = array(
                    'cb' => '<input type="checkbox" />', // to display the checkbox.
                    'id' => 'ID',
                    'name' => __('Ingredient name', 'wp-my-recipe') ,
                    'kcalories' => __('Kilocalories per 100 ml/mg', 'wp-my-recipe') ,
                    'reference' => __('Reference value', 'wp-my-recipe')
                );
                return $columns;
                }

            /**
             * Define which columns are hidden
             *
             * @return Array
             */
            public

            function get_hidden_columns()
                {
                return array(
                    'id'
                );
                }

            /**
             * Define the sortable columns
             *
             * @return Array
             */
            public

            function get_sortable_columns()
                {
                return array(
                    'name' => array(
                        'name',
                        false
                    ) ,
                    'kcalories' => array(
                        'kcalories',
                        false
                    ) ,
                    'reference' => array(
                        'reference',
                        false
                    ) ,
                );
                }

            /**
             * Get the table data
             *
             * @return Array
             */
            function table_data($search = NULL)
                {

                // todo add real search

                if ($search != NULL)
                    {
                    $search = trim($search);
                    $data = array(
                        ['id' => 'dummyData',
                        'name' => $search,
                        'kcalories' => 'dummyData',
                        'reference' => 'dummyData']
                    );
                    }
                  else
                    {
                    $data = s_getAllIngredients();
                    }

                return $data;
                }

            /**
             * Define what data to show on each column of the table
             *
             * @param  Array $item        Data
             * @param  String $column_name - Current column name
             *
             * @return Mixed
             */
            public

            function column_default($item, $column_name)
                {
                switch ($column_name)
                    {
                case 'id':
                case 'name':
                case 'kcalories':
                case 'reference':
                    return $item[$column_name];
                default:
                    return print_r($item, true);
                    }
                }

            // /**
            //  * Allows you to sort the data by the variables set in the $_GET
            //  *
            //  * @return Mixed
            //  */

            private
            function sort_data($a, $b)
                {

                // Set defaults

                $orderby = 'name';
                $order = 'asc';

                // If orderby is set, use this as the sort column

                if (!empty($_GET['orderby']))
                    {
                    $orderby = $_GET['orderby'];
                    }

                // If order is set use this as the order

                if (!empty($_GET['order']))
                    {
                    $order = $_GET['order'];
                    }

                $result = strcmp($a[$orderby], $b[$orderby]);
                if ($order === 'asc')
                    {
                    return $result;
                    }

                return -$result;
                }

            protected
            function column_cb($item)
                {
                return sprintf('<label class="screen-reader-text" for="ingredient_' . $item['id'] . '">' . sprintf(__('Select %s') , $item['name']) . '</label>' . "<input type='checkbox' name='ingredient[]' id='ingredient_{$item['id']}' value='{$item['id']}' />");
                }
            }

        $myListTable = new My_List_Table();

        // Fetch, prepare, sort, and filter our data...

        if (isset($_POST['s']))
            {
            $myListTable->prepare_items($_POST['s']);
            }
          else
            {
            $myListTable->prepare_items();
            }

        echo "<form role='search' method='post' id='searchform'>";
        $myListTable->search_box("Search", "search_post_id");
        echo "</form>";
        $myListTable->display();
...