Hi You, I am Tade

You are here: Home / Wordpress / Thêm bộ lọc taxonomy trong admin custom post type

Thêm bộ lọc taxonomy trong admin custom post type

28 May, 2017 by Hoàng Thức

Đây là đoạn code nhỏ dùng để tạo bộ lọc custom taxonomy trong admin custom post type CMS wordpress. Để có thể dễ dàng quản lý bài viết trên site. Giao diện như bên dưới.

Vẫn như củ các bạn copy code và đặt vào file functions.php thôi nhưng chú ý 1 số thông số như sau:

1.Hook : Mình sử dung 2 hook là restrict_manage_posts và parse_query.

restrict_manage_posts để lấy data taxonomy và hiển thị ra dạng dropdown taxonomy

parse_query cải tạo lại bộ lọc để nó có thể filter thêm cái taxonomy mình mới thêm.

2.Biến: Bạn thay biến post_type và taxonomy thành của mình để sử dụng nhé.

3.Code đây


add_action('restrict_manage_posts', 'tsm_filter_post_type_by_taxonomy');
function tsm_filter_post_type_by_taxonomy() {
 global $typenow;
 $post_type = 'project'; // change to your post type
 $taxonomy = 'kind'; // change to your taxonomy
 if ($typenow == $post_type) {
 $selected = isset($_GET[$taxonomy]) ? $_GET[$taxonomy] : '';
 $info_taxonomy = get_taxonomy($taxonomy);
 wp_dropdown_categories(array(
 'show_option_all' => __("Lọc {$info_taxonomy->label}"),
 'taxonomy' => $taxonomy,
 'name' => $taxonomy,
 'orderby' => 'name',
 'selected' => $selected,
 'show_count' => true,
 'hide_empty' => true,
 ));
 };
}
/**
 * Filter posts by taxonomy in admin
 * @author Hoang Thuc
 * @link https://hoangthuc.com/bo-loc-taxonomy-trong-admin-custom-post
 */
add_filter('parse_query', 'tsm_convert_id_to_term_in_query');
function tsm_convert_id_to_term_in_query($query) {
 global $pagenow;
 $post_type = 'project'; // change to your post type
 $taxonomy = 'kind'; // change to your taxonomy
 $q_vars = &$query->query_vars;
 if ( $pagenow == 'edit.php' && isset($q_vars['post_type']) && $q_vars['post_type'] == $post_type && isset($q_vars[$taxonomy]) && is_numeric($q_vars[$taxonomy]) && $q_vars[$taxonomy] != 0 ) {
 $term = get_term_by('id', $q_vars[$taxonomy], $taxonomy);
 $q_vars[$taxonomy] = $term->slug;
 }
} 

Chúc các bạn thành công !

Filed Under: Custom post wordpress, Wordpress, Wordpress nâng cao Tagged With: Taxonomy filter admin custom post

  • Home
  • Về tôi
  • Liên hệ

Danh mục

  • Blog
  • Lập trình
  • Laravel
  • MYSQL
  • Php
  • Thủ thuật máy tính
  • Vps
    • DirectAdmin
  • Wordpress
    • Plugin wordpress
    • Wordpress căn bản
    • Wordpress nâng cao
      • Custom post wordpress

Archives

  • October 2021
  • January 2021
  • December 2020
  • November 2020
  • September 2020
  • August 2020
  • September 2019
  • August 2019
  • July 2019
  • June 2018
  • August 2017
  • July 2017
  • June 2017
  • May 2017
  • March 2017
  • November 2016
  • September 2016
  • July 2016
  • June 2016
  • May 2016
  • April 2016
  • March 2016
  • January 2016
  • December 2015
  • May 2015
  • April 2015
Copyright © 2023 · HoangThuc.com · Genesis Framework