เคนเจอปัญหาตอนนี้ก็คือในกรณีที่สร้าง Custom Post Types ขึ้นมาด้วยปลั๊กอิน Custom Post Type UI แล้ว ก็พบว่าทำยังไงมันก็ไม่มีตัวกรองให้เราเหมือนในเรื่องอ่ะ

ก็ไปเจอโค้ดที่มีคนทำไว้ให้แล้ว ก็เลยเอามาแบ่งกันเลยดีกว่า จะได้ง่าย ๆ ขอบคุณวิธีทำจาก GenerateWP ครับ

ตัวอย่างนี้เคนสร้าง Custom Post Types ชื่อว่า คลังความรู้ (post type slug: knowledgebase) และ หมวดหมู่ของมัน (slug: klbcategory)

ตอนนี้ก็จะเห็นว่ามันไม่มี ตัวกรองของหมวดหมู่ให้เราอ่ะ อยากได้ตัวกรองตรงนี้ด้วย!!


ก็ไปเพิ่มโค้ดชุดนี้ที่ธีม หรือปลั๊กอินได้ตามสบายเลยครับ ส่วนของเคนเองจะเพิ่มต่อท้ายไว้ในไฟล์ functions.php ในธีมที่ใช้

function filter_knowledgebase_by_taxonomies( $post_type, $which ) {

  // ถ้าไม่ใช่ Post type ที่เราต้องการก็ไม่ต้องทำอะไร
  if ( 'knowledgebase' !== $post_type ) return;

  // เลือก taxonomies ที่ต้องการสร้างตัวกรอง
  $taxonomies = array( 'klbcategory' );

  foreach ( $taxonomies as $taxonomy_slug ) {

    // รับค่า taxonomies
    $taxonomy_obj = get_taxonomy( $taxonomy_slug );
    $taxonomy_name = $taxonomy_obj->labels->name;

    // รับค่า taxonomy terms
    $terms = get_terms( $taxonomy_slug );

    // สร้างตัวกรอง
    echo "<select name='{$taxonomy_slug}' id='{$taxonomy_slug}' class='postform'>";
    echo '<option value="">' . sprintf( esc_html__( '%sทั้งหมด', 'text_domain' ), $taxonomy_name ) . '</option>';
    foreach ( $terms as $term ) {
      printf(
        '<option value="%1$s" %2$s>%3$s (%4$s)</option>',
	$term->slug,
	( ( isset( $_GET[$taxonomy_slug] ) && ( $_GET[$taxonomy_slug] == $term->slug ) ) ? ' selected="selected"' : '' ),
	$term->name,
	$term->count
      );
    }
    echo '</select>';
  }
}

// ใช้ action ชื่อ restrict_manage_posts
add_action( 'restrict_manage_posts', 'filter_knowledgebase_by_taxonomies' , 10, 2);

ตอนนี้มันก็จะแสดงตัวกรองออกมาแล้วววววว

0 0 votes
Article Rating
0
Would love your thoughts, please comment.x
()
x