Thêm Bulk Actions trong bảng quản lý bài viết WordPress

Cập nhật lần cuối vào

Bulk Actions là tính năng quản lý nhiều bài viết đã được chọn cùng lúc, bạn có thể thực thi một lệnh nào đó đối với các bài viết trong danh sách. Hiện tại, WordPress có hỗ trợ filter bulk_actions cho bạn, nhưng bạn chưa được phép thêm thuộc tính mới mà chỉ có thể chỉnh sửa hoặc xóa các thuộc tính cũ.

Thêm Bulk Actions trong WordPress

Với Bulk Actions, bạn có thể thực thi cùng một lúc một thao tác nào đó cho nhiều bài viết đã được chọn. Cái này rật tiện lợi cho bạn trong khâu quản lý bài viết, bạn không phải vào từng bài viết để thay đổi thông tin.

function hocwp_content_captcha_custom_bulk_admin_footer() {
    global $post_type;
    $post_types = hocwp_content_captcha_get_post_types();
    if(in_array($post_type, $post_types)) {
        ?>
        <script type="text/javascript">
            (function($) {
                var actions = [['content_captcha', 'Content captcha'], ['remove_content_captcha', 'Remove content captcha']];
                hocwp.addBulkAction(actions);
            })(jQuery);
        </script>
        <?php
    }
}
add_action('admin_footer-edit.php', 'hocwp_content_captcha_custom_bulk_admin_footer');

Đầu tiên, bạn sử dụng action admin_footer-edit.php để thêm script vào chân trang của bảng điều khiển admin, cái này chỉ chạy khi bạn đang ở trang edit.php. Trong hàm này, bạn kiểm tra xem post type hiện tại của bạn xem có nằm trong danh sách những post type bạn muốn thêm Bulk Actions hay không.

hocwp.addBulkAction = function(actions) {
	actions = actions || [];
	for(var i = 0; i < actions.length; i++) {
		$('<option>').val(actions[i][0]).text(actions[i][1]).appendTo("select[name='action']");
		$('<option>').val(actions[i][0]).text(actions[i][1]).appendTo("select[name='action2']");
	}
};

Hàm thêm bulk action bạn có thể viết đơn giản như bên trên, tham số đầu vào là một mảng các bulk action, bạn lặp tất cả các đối tượng này, sau đó tạo một thẻ option và thêm vào 2 mục Bulk Actions của WordPress, ở phía trên và dưới của table.

function hocwp_content_captcha_custom_bulk_action() {
    global $typenow;
    $post_type = $typenow;
    $post_types = hocwp_content_captcha_get_post_types();
    if(!in_array($post_type, $post_types)) {
        return;
    }
    $wp_list_table = _get_list_table('WP_Posts_List_Table');
    $action = $wp_list_table->current_action();
    $allowed_actions = array('content_captcha', 'remove_content_captcha');
    if(!in_array($action, $allowed_actions)) {
        return;
    }
    check_admin_referer('bulk-posts');
    $post_ids = '';
    if(isset($_REQUEST['post'])) {
        $post_ids = array_map('intval', $_REQUEST['post']);
    }
    if(!is_array($post_ids)) {
        return;
    }
    $sendback = remove_query_arg(array('selected', 'untrashed', 'deleted', 'ids'), wp_get_referer());
    if(!$sendback) {
        $sendback = admin_url('edit.php?post_type=' . $post_type);
    }
    $pagenum = $wp_list_table->get_pagenum();
    $sendback = add_query_arg(array('paged' => $pagenum, 'selected' => count($post_ids), 'ids' => join(',', $post_ids)), $sendback);
    switch($action) {
        case 'content_captcha':
            foreach($post_ids as $post_id) {
                update_post_meta($post_id, 'content_captcha', 1);
            }
            $sendback = add_query_arg(array('content_captcha' => 1), $sendback);
            break;
        case 'remove_content_captcha':
            foreach($post_ids as $post_id) {
                update_post_meta($post_id, 'content_captcha', 0);
            }
            $sendback = add_query_arg(array('remove_content_captcha' => 1), $sendback);
            break;
        default:
            return;
    }
    $sendback = remove_query_arg(array('action', 'action2', 'tags_input', 'post_author', 'comment_status', 'ping_status', '_status', 'post', 'bulk_edit', 'post_view'), $sendback);
    wp_redirect($sendback);
    exit();
}
add_action('load-edit.php', 'hocwp_content_captcha_custom_bulk_action');

Tiếp đến, bạn dùng action load-edit.php để kiểm tra và thực thi hàm. Trong hàm thực thi lệnh này, bạn cũng sẽ kiểm tra xem post type có hợp lệ hay không, sau đó bạn kiểm tra xem action có phải là của bạn tạo hay không, và tùy vào từng action khác nhau mà chạy lệnh cho hợp lệ. Cuối cùng là bạn sẽ chuyển tiếp sang url của trang hiện tại với các tham số truyền trên đường dẫn.

function hocwp_content_captcha_bulk_action_admin_notice() {
    global $post_type, $pagenow;
    $post_types = hocwp_content_captcha_get_post_types();
    if('edit.php' == $pagenow) {
        if(!in_array($post_type, $post_types)) {
            return;
        }
        $selected = isset($_REQUEST['selected']) ? $_REQUEST['selected'] : 0;
        $selected = absint($selected);
        if($selected > 0 && (isset($_REQUEST['content_captcha']) || isset($_REQUEST['remove_content_captcha']))) {
            $message = $selected;
            if($selected > 1) {
                $message .= ' posts';
            } else {
                $message .= ' post';
            }

            if(isset($_REQUEST['content_captcha'])) {
                $message .= ' marked';
            } elseif(isset($_REQUEST['remove_content_captcha'])) {
                $message .= ' unmarked';
            }

            $message .= ' using captcha to confirm before viewing the content.';

            $args = array(
                'text' => $message,
                'dismissible' => true
            );
            hocwp_admin_notice($args);
        }
    }
}
add_action('admin_notices', 'hocwp_content_captcha_bulk_action_admin_notice');

Cuối cùng là bạn sẽ tạo thông báo cho người dùng bằng action admin_notices, trong hàm này bạn sẽ kiểm tra xem trang hiện tại có phải là trang edit.php hay không? Sau đó bạn kiểm tra xem post type có hợp lệ hay không, cuối cùng là bạn kiểm tra các tham số trong url trả về xem có phải là lệnh của bạn thực thi hay không?

Như vậy là bạn đã có thể tạo được một Bulk Actions hoàn chỉnh trong WordPress, trong ví dụ này mình có sử dụng các hàm mình đã xây dựng sẵn trong gói hocwp do bên mình thực hiện, vì thế nên bạn cần thay đổi làm hàm cho hợp lý để không dính lỗi gọi hàm chưa được khai báo trong PHP, chúc bạn thành công.

5/5 - (1 bình chọn)