Multiple Post Types & Organized JSON Structure
Search Multiple Post Types Sekaligus
post_type sebagai Array:
php
$mainQuery = new WP_Query(array(
'post_type' => array('post', 'page', 'professor', 'program', 'event', 'campus'),
's' => sanitize_text_field($data['term'])
));Aktifkan REST API untuk Custom Post Types
Tambahkan 'show_in_rest' => true di registrasi CPT (mu-plugins/university-post-types.php):
php
register_post_type('professor', array(
// ... setting lainnya
'show_in_rest' => true
));Organisasi: Sub-Arrays per Post Type
Daripada semua results tercampur, buat sub-arrays terpisah:
php
function university_search_results($data) {
$mainQuery = new WP_Query(array(
'post_type' => array('post', 'page', 'professor', 'program', 'event', 'campus'),
's' => sanitize_text_field($data['term'])
));
$results = array(
'generalInfo' => array(),
'professors' => array(),
'programs' => array(),
'events' => array(),
'campuses' => array()
);
while ($mainQuery->have_posts()) {
$mainQuery->the_post();
if (get_post_type() == 'post' OR get_post_type() == 'page') {
array_push($results['generalInfo'], array(
'title' => get_the_title(),
'permalink' => get_the_permalink(),
'postType' => get_post_type(),
'authorName' => get_the_author()
));
}
if (get_post_type() == 'professor') {
array_push($results['professors'], array(
'title' => get_the_title(),
'permalink' => get_the_permalink(),
'image' => get_the_post_thumbnail_url(0, 'professorLandscape')
));
}
if (get_post_type() == 'program') {
array_push($results['programs'], array(
'title' => get_the_title(),
'permalink' => get_the_permalink(),
'id' => get_the_ID()
));
}
if (get_post_type() == 'event') {
$eventDate = new DateTime(get_field('event_date'));
$description = null;
if (has_excerpt()) {
$description = get_the_excerpt();
} else {
$description = wp_trim_words(get_the_content(), 18);
}
array_push($results['events'], array(
'title' => get_the_title(),
'permalink' => get_the_permalink(),
'month' => $eventDate->format('M'),
'day' => $eventDate->format('d'),
'description' => $description
));
}
if (get_post_type() == 'campus') {
array_push($results['campuses'], array(
'title' => get_the_title(),
'permalink' => get_the_permalink()
));
}
}
return $results;
}Struktur JSON Hasil:
json
{
"generalInfo": [
{ "title": "About Us", "permalink": "...", "postType": "page", "authorName": "Brad" }
],
"professors": [
{ "title": "Dr. Barks A Lot", "permalink": "...", "image": "...jpg" }
],
"programs": [
{ "title": "Biology", "permalink": "...", "id": 97 }
],
"events": [
{ "title": "Science of Cats", "permalink": "...", "month": "Jan", "day": "15", "description": "..." }
],
"campuses": []
}Keuntungan Struktur Ini:
- Data sudah terorganisir per post type
- Front-end JavaScript mudah mengakses:
results.generalInfo,results.professors, dll. - Siap untuk 3-column layout di search overlay
- Setiap post type bisa punya property berbeda sesuai kebutuhan display