WP_LIST_TABLE BULK_ACTION获取编辑并删除

时间:2017-05-03 作者:CompactCode

很明显,我没有得到有关这方面的文件。即使是其他关于它的堆栈交换,我也不太清楚。我想这是因为我不明白这是怎么回事

因此,我正在创建一个管理页面,并读取我创建的数据库表。我只是不知道如何在Wordpress框架内进行单次删除(和编辑)和批量删除(和编辑)。

下面是代码:

class Designit_Countries_Table extends Designit_List_Table
{

    private $order;
    private $orderby;
    private $posts_per_page = 25;

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

        parent :: __construct(array(
            \'singular\' => "country",
            \'plural\' => "countries",
            \'ajax\' => true
        ));

        $this->set_order();
        $this->set_orderby();
    }

    private function get_sql_results()
    {
        global $wpdb;
        $args = array(\'id\', \'name\', \'title\', \'country\', \'image\', \'time\');
        $sql_select = implode(\', \', $args);
        $sql_results = $wpdb->get_results("SELECT " . $sql_select . " FROM " . $wpdb->prefix . "designitcountries ORDER BY $this->orderby $this->order ");
        return $sql_results;
    }

    public function set_order()
    {
        $order = \'ASC\';
        if (isset($_GET[\'order\']) AND $_GET[\'order\'])
            $order = $_GET[\'order\'];
        $this->order = esc_sql($order);
    }

    public function set_orderby()
    {
        $orderby = \'id\';
        if (isset($_GET[\'orderby\']) AND $_GET[\'orderby\'])
            $orderby = $_GET[\'orderby\'];
        $this->orderby = esc_sql($orderby);
    }

    public function ajax_user_can()
    {
        return current_user_can(\'edit_posts\');
    }

    public function no_items()
    {
        _e(\'No countries found.\');
    }

    public function get_views()
    {
        return array();
    }

    public function get_columns()
    {
        $columns = array(
            \'cb\' => \'<input type="checkbox" />\',
            \'name\' => __(\'Name\'),
            \'title\' => __(\'Title\'),
            \'country\' => __(\'Country\'),
            \'image\' => __(\'Image\'),
            \'time\' => __(\'Created on\'),
            \'id\' => __(\'id\')
        );
        return $columns;
    }

    function get_bulk_actions() {
        $actions = array(
            \'delete\'    => \'Delete\'
        );
        return $actions;
    }
    public function get_sortable_columns()
    {
        $sortable = array(
            \'id\' => array(\'id\', true),
            \'title\' => array(\'Title\', true),
            \'name\' => array(\'Name\', true),
            \'country\' => array(\'Country\', true),
            \'image\' => array(\'Image\', true),
            \'time\' => array(\'Created on\', true),
        );
        return $sortable;
    }

    public function prepare_items()
    {
        $columns = $this->get_columns();
        $hidden = array();
        $sortable = $this->get_sortable_columns();
        $this->_column_headers = array(
            $columns,
            $hidden,
            $sortable
        );

        // SQL results
        $posts = $this->get_sql_results();
        empty($posts) AND $posts = array();

        # >>>> Pagination
        $per_page = $this->posts_per_page;
        $current_page = $this->get_pagenum();
        $total_items = count($posts);
        $this->set_pagination_args(array(
            \'total_items\' => $total_items,
            \'per_page\' => $per_page,
            \'total_pages\' => ceil($total_items / $per_page)
        ));
        $last_post = $current_page * $per_page;
        $first_post = $last_post - $per_page + 1;
        $last_post > $total_items AND $last_post = $total_items;

        // Setup the range of keys/indizes that contain
        // the posts on the currently displayed page(d).
        // Flip keys with values as the range outputs the range in the values.
        $range = array_flip(range($first_post - 1, $last_post - 1, 1));

        // Filter out the posts we\'re not displaying on the current page.
        $posts_array = array_intersect_key($posts, $range);
        # <<<< Pagination
        // Prepare the data
        $permalink = __(\'Edit:\');
        foreach ($posts_array as $key => $post) {
            $link = get_edit_post_link($post->id);
            $no_name = __(\'No name set\');
            $name = !$post->name ? "<em>{$no_name}</em>" : $post->name;
            $posts[$key]->name = "{$name}";
        }
        $this->items = $posts_array;

        $this->process_bulk_action();

    }

    /**
     * A single column
     */
    public function column_default($item, $column_name)
    {
        return $item->$column_name;
    }


    /**
     * Disables the views for \'side\' context as there\'s not enough free space in the UI
     * Only displays them on screen/browser refresh. Else we\'d have to do this via an AJAX DB update.
     *
     * @see WP_List_Table::extra_tablenav()
     */
    public function extra_tablenav($which)
    {
        global $wp_meta_boxes;
        $views = $this->get_views();
        if (empty($views)) return;

        $this->views();
    }

    //edit buttons

    function column_name(){
        global $wpdb;
        $args = array(\'id\', \'name\');
        $sql_select = implode(\', \', $args);
        $sql_results = $wpdb->get_results("SELECT " . $sql_select . " FROM " . $wpdb->prefix . "designitcountries ORDER BY $this->orderby $this->order ");

        foreach ($sql_results as $sql_result) {
            $name = $sql_result->name;
            $id = $sql_result->id;
            $actions = array(
                \'edit\' => sprintf(\'<a href="?page=%s&action=%s&name=%s">Edit</a>\', $_REQUEST[\'page\'], \'edit\', $id),
                \'delete\' => sprintf(\'<a href="?page=%s&action=%s&name=%s">Delete</a>\', $_REQUEST[\'page\'], \'delete\', $id),
            );
            return sprintf(\'%1$s %2$s\', $name, $this->row_actions($actions));
        }
    }

    function column_cb($item) {
            return sprintf(
                \'<input type="checkbox" name="book[]" value="%s" />\',
                $this->_args[\'singular\'],
                $item->id
            );
        }

    public function process_bulk_action() {

        // security check!
        if ( isset( $_POST[\'_wpnonce\'] ) && ! empty( $_POST[\'_wpnonce\'] ) ) {

            $nonce  = filter_input( INPUT_POST, \'_wpnonce\', FILTER_SANITIZE_STRING );
            $action = \'bulk-\' . $this->_args[\'plural\'];

            if ( ! wp_verify_nonce( $nonce, $action ) )
                wp_die( \'Nope! Security check failed!\' );

        }

        $action = $this->current_action();

        switch ( $action ) {

            case \'delete\':
                foreach($_GET[\'country\'] as $country) {



                }

                wp_die( \'You have deleted this succesfully\' );
                break;

            case \'edit\':
                wp_die( \'This is the edit page.\' );
                break;

            default:
                // do nothing or something else
                return;
                break;
        }

        return;
    }

}
这有很多代码需要处理,所以让我把我的问题分成几部分。

结果表明:Countries admin page

这显示了我创建的国家/地区页面,其中包含我现在已执行的操作和复选框

所以我实现了如下复选框:

public function get_columns()
{
    $columns = array(
        \'cb\' => \'<input type="checkbox" />\',
        \'name\' => __(\'Name\'),
        \'title\' => __(\'Title\'),
        \'country\' => __(\'Country\'),
        \'image\' => __(\'Image\'),
        \'time\' => __(\'Created on\'),
        \'id\' => __(\'id\')
    );
    return $columns;
}
    function column_cb($item) {
        return sprintf(
            \'<input type="checkbox" name="book[]" value="%s" />\',
            $this->_args[\'singular\'],
            $item->id
        );
    }
然后我还有一个编辑和删除按钮:

function column_name(){
    global $wpdb;
    $args = array(\'id\', \'name\');
    $sql_select = implode(\', \', $args);
    $sql_results = $wpdb->get_results("SELECT " . $sql_select . " FROM " . $wpdb->prefix . "designitcountries ORDER BY $this->orderby $this->order ");

    foreach ($sql_results as $sql_result) {
        $name = $sql_result->name;
        $id = $sql_result->id;
        $actions = array(
            \'edit\' => sprintf(\'<a href="?page=%s&action=%s&name=%s">Edit</a>\', $_REQUEST[\'page\'], \'edit\', $id),
            \'delete\' => sprintf(\'<a href="?page=%s&action=%s&name=%s">Delete</a>\', $_REQUEST[\'page\'], \'delete\', $id),
        );
        return sprintf(\'%1$s %2$s\', $name, $this->row_actions($actions));
    }
}
以及批量操作和处理:

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

public function process_bulk_action() {

        // security check!
        if ( isset( $_POST[\'_wpnonce\'] ) && ! empty( $_POST[\'_wpnonce\'] ) ) {

            $nonce  = filter_input( INPUT_POST, \'_wpnonce\', FILTER_SANITIZE_STRING );
            $action = \'bulk-\' . $this->_args[\'plural\'];

            if ( ! wp_verify_nonce( $nonce, $action ) )
                wp_die( \'Nope! Security check failed!\' );

        }

        $action = $this->current_action();

        switch ( $action ) {

            case \'delete\':
                foreach($_GET[\'country\'] as $country) {



                }

                wp_die( \'You have deleted this succesfully\' );
                break;

            case \'edit\':
                wp_die( \'This is the edit page.\' );
                break;

            default:
                // do nothing or something else
                return;
                break;
        }

        return;
    }

Now where i don\'t get it

我确实知道我需要在“delete”的情况下进行删除,在“edit”的情况下进行编辑。但我不知道如何选择已使用复选框选中的行以实际删除。或者,如果使用“删除按钮”而不是批量操作,则仅删除该行以及编辑功能的总体工作方式。

似乎也找不到合适的例子,所以我希望你们中的一个能帮助我!

按“delete”(删除)时看到的页面:enter image description here

Update

所以我通过给每样东西都赋予它自己的ID(这很有意义)来让它工作

function column_cb($item) {
    return sprintf(
        \'<input type="checkbox" name="country[]" value="%s" />\',
        $item->id
    );
}
function column_name($item){
    $item_json = json_decode(json_encode($item), true);
    $actions = array(
        \'edit\' => sprintf(\'<a href="?page=%s&action=%s&id=%s">Edit</a>\', $_REQUEST[\'page\'], \'edit\', $item_json[\'id\']),
        \'delete\' => sprintf(\'<a href="?page=%s&action=%s&id=%s">Delete</a>\', $_REQUEST[\'page\'], \'delete\', $item_json[\'id\']),
    );
    return \'<em>\' . sprintf(\'%s %s\', $item_json[\'name\'], $this->row_actions($actions)) . \'</em>\';
}
然后使用该引用删除带有SQL查询的表:

 case \'delete\':
                global $wpdb;
                $table_name = $wpdb->prefix . \'designitcountries\';
                $ids = isset($_REQUEST[\'id\']) ? $_REQUEST[\'id\'] : array();
                var_dump($ids);
                    if (is_array($ids)) $ids = implode(\',\', $ids);
                    if (!empty($ids)) {
                        $wpdb->query("DELETE FROM $table_name WHERE id IN($ids)");
                }

                wp_die( \'You have deleted this succesfully\' );
                break;

BUT

当我使用“删除”按钮时,它会起作用,但当我执行批量操作删除时,它不会起作用(甚至当我选择1时也不会起作用)

我确实在“删除”按钮的A href的URL中提供了ID。不知道我该如何用复选框来做同样的事情

1 个回复
SO网友:CompactCode

所以,我发现了问题。

首先,我没有在复选框或按钮上选择正确的ID,因此我改为使用代码:

function column_name($item){
    $item_json = json_decode(json_encode($item), true);
    $actions = array(
        \'edit\' => sprintf(\'<a href="?page=%s&action=%s&id=%s">Edit</a>\', $_REQUEST[\'page\'], \'edit\', $item_json[\'id\']),
        \'delete\' => sprintf(\'<a href="?page=%s&action=%s&id=%s">Delete</a>\', $_REQUEST[\'page\'], \'delete\', $item_json[\'id\']),
    );
    return \'<em>\' . sprintf(\'%s %s\', $item_json[\'name\'], $this->row_actions($actions)) . \'</em>\';
}
注意这里我有$items 现在,世卫组织将获得所需的所有数据。我将进行JSON解码和编码,将其转换为一个数组,然后调用JSON数组idnamesprinttf() 在我需要的地方。

复选框相同(不带JSON):

function column_cb($item) {
        return sprintf(
            \'<input type="checkbox" name="id[]" value="%s" />\',
            $item->id
        );
    }
之后,我将此添加到我的案例“删除”:

case \'delete\':
                global $wpdb;
                $table_name = $wpdb->prefix . \'designitcountries\';

                if (\'delete\' === $this->current_action()) {
                    $ids = isset($_REQUEST[\'id\']) ? $_REQUEST[\'id\'] : array();
                    if (is_array($ids)) $ids = implode(\',\', $ids);

                    if (!empty($ids)) {
                        $wpdb->query("DELETE FROM $table_name WHERE id IN($ids)");
                    }
                }

                wp_die( \'You have deleted this succesfully\' );
                break;
现在我有了一个从按钮和复选框中删除的工作方法。

相关推荐

Database problem

我的数据库有问题。首页工作正常,但当我想访问backoffice mysite时。com/wp admin我正在重定向到/wp admin/install。因此,我打开了phpmyadmin,看到有一个空数据库。。没有列,没有行,只有前端站点和所有页面工作正常吗?XD。发生了什么事?我有w3 total缓存和云flare。也许我的网站只因为我的数据库被缓存而工作?如何恢复数据库?请帮帮我,我没有备份。