Skip to content
Thuan Bui's Blog
Go back

Thêm dropdown filter cho post tag trong WordPress admin panel

Mặc định trang hiển thị danh sách bài viết của WordPress admin panel chỉ có các mục lọc bài viết theo ngày (Date), danh mục (Category),… không có mục chọn cho post tag.

Để thêm một cột mới để lọc bài viết theo tag, sử dụng code snippets sau

Terminal window
// Add dropdown filters for multiple taxonomies in the admin post list
function add_taxonomy_filters_dropdown($taxonomies = [], $post_type ) {
global $typenow;
if ($typenow !== $post_type) {
return;
}
foreach ($taxonomies as $taxonomy) {
$taxonomy_object = get_taxonomy($taxonomy);
if (!$taxonomy_object) {
continue;
}
$terms = get_terms([
'taxonomy' => $taxonomy,
'hide_empty' => true,
]);
if ($terms) {
echo '<select name="' . esc_attr($taxonomy) . '" id="filter-by-' . esc_attr($taxonomy) . '">';
echo '<option value="">' . sprintf(__('All %s', 'textdomain'), esc_html($taxonomy_object->labels->name)) . '</option>';
foreach ($terms as $term) {
$selected = isset($_GET[$taxonomy]) && $_GET[$taxonomy] == $term->slug ? ' selected="selected"' : '';
printf('<option value="%s"%s>%s</option>', esc_attr($term->slug), $selected, esc_html($term->name));
}
echo '</select>';
}
}
}
add_action('restrict_manage_posts', function () {
add_taxonomy_filters_dropdown(['post_tag'], 'post'); // Replace 'post_tag' and 'post' with your desired taxonomy & post type
});

Bạn có thể thêm đoạn code này vào file functions.php của theme, hoặc dùng plugin Code Snippets.

Một cột mới đã hiện ra trong phần filter của bài viết.

Bạn có thể chỉnh lại dòng 33 để thay thế taxonomy và post_type tương ứng. Ví dụ đổi như sau để hiển thị cột filter cho thương hiệu sản phẩm trên trang sản phẩm

add_taxonomy_filters_dropdown(['product_brand'], 'product');

Chúc bạn thực hiện thành công!


Share this post on:

Previous Post
Dọn dẹp systemd journal log trên Linux
Next Post
Hướng dẫn cấu hình Hairpin NAT (NAT Loopback) trên router OpenWRT