Hiển thị cả Post và Custom Post Types trong Archives.php

Mặc định Archives.php chỉ hiển thị các bài viết dạng post nhưng bạn có thể cho hiển thị cả Custom Post Types bằng cách thêm vào file functions.php đoạn code sau đây:

function custom_post_types_in_archives ( $query ) {
if( is_category() || is_tag() && empty( $query->query_vars['suppress_filters'] ) ) {
$query->set( 'post_type', array(
'post', 'nav_menu_item', 'custom-post-type-1', 'custom-post-type-2'
));
return $query;
}
}
add_filter( 'pre_get_posts', 'custom_post_types_in_archives' );

Hoặc sử dụng code này:

// Add custom post types to archives
function custom_post_archive($query) {
if ($query->is_archive)
$query->set( 'post_type', array('your_custom_type_1', 'your_custom_type_2', 'nav_menu_item', 'post') );
remove_action( 'pre_get_posts', 'custom_post_archive' );
}
add_action('pre_get_posts', 'custom_post_archive');

Nhớ sửa custom-post-type-1custom-post-type-1 thành các custom post types của bạn nhé. Nếu muốn thêm nhiều hơn thì cứ ngăn cách nhau bằng dấu phẩy như mẫu code trên là được.

Tất nhiên, nếu bạn muốn hiển thị cả Custom Post Types trong kết quả tìm kiếm thì thêm đoạn code này:

//Custom Post Types trong kết quả tìm kiếm
function searchAll( $query ) {
if ( $query->is_search ) {
$query->set( 'post_type', array( 'post', 'page', 'feed', 'custom_post_type1', 'custom_post_type2'));
}
return $query;
}

// The hook needed to search ALL content
add_filter( 'the_search_query', 'searchAll' );

Chúc bạn thành công.

Theo dõi bài viết
Nhận thông báo
guest
0 Bình luận
Inline Feedbacks
Xem tất cả bình luận
0
Gửi bình luận của bạn về bài viết này.x