[WordPress] แก้ปัญหา Custom Post Type ไม่แสดงในหน้า Custom Taxonomy Archive

เจอปัญหาล่าสุด ที่หาวิธีแก้อยู่หลายชั่วโมง นั่นคือ ทำหน้า Archive ของ Custom Taxonomy ก็ตั้งชื่อไฟล์ว่า taxonomy-xxx.php ตามปกติ

ส่วนในไฟล์นั้นก็เป็น Loop ปกติเช่นกัน ใช้ have_posts() ธรรมดา ๆ เหมือน archive.php เลย

แต่มีปัญหาว่า URL ก็ถูกแล้ว (เพราะ taxonomy-xxx.php ถูกเรียกมาใช้) แต่ทำยังไงก็ไม่มีโพสขึ้นมาแสดง ทั้งที่หลังบ้านเซ็ตไว้แล้ว

ตอนแรกก็นึกว่าไปทำผิดตอน register post type หรือ register taxonomy หรือเปล่า เสิร์จหาวิธีแก้อยู่นานก็ไม่เจออะไรผิดเพราะ public ก็ true, publicly_queryable ก็ true, query_var ก็ true, has_archive ก็ true ไม่น่าจะลืมอะไรแล้ว

เค้าบอกให้กดเซฟ Permalink บ่อย ๆ ก็กดตาม แต่ไม่ช่วยอะไรอยู่ดี

สุดท้ายเสิร์จไปเจอกระทู้ฝรั่ง https://wordpress.org/support/topic/custom-post-types-not-showing-up-on-taxonomy-archives-and-search-results

ซึ่งวิธีแก้ไม่มีไรเลย แค่ใส่ 2 บรรทัดนี้ไปหลัง get_header(); ของไฟล์ taxonomy-xxx.php ก็เสร็จแล้ว

// Make Custom Post Type in Custom Taxonomy Works
global $query_string;
query_posts($query_string . "&post_type=any");

ใช้เวลาหาทั้งหมด 3 ชั่วโมง T_____T #จบข่าว

อัพเดท

ตอนทำ Pagination เรา hook อันนี้เข้าไปได้

function custom_posts_per_page($query)
{   
    if(is_tax('news-category')){
    //Tax Page
    $query->query_vars['post_type'] = 'any';
    $query->query_vars['posts_per_page'] = 4;	
  }

    return $query;
}

if( !is_admin() )
{
    add_filter( 'pre_get_posts', 'custom_posts_per_page' );
}

Posted

in

,

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *