Conditional Logic Within Template Literal & URL Fleksibel
Masalah: Search Tanpa Hasil
Jika search tidak menemukan apapun, WordPress mengembalikan array kosong []. Hasilnya: heading "General Information" muncul tapi kosong — tidak ada pesan "tidak ditemukan".
Ternary Operator (Pengganti If Statement)
Aturan Penting
Tidak boleh menggunakan
ifstatement di dalam template literal. Gunakan ternary operator sebagai gantinya.
Sintaks Ternary Operator:
js
condition ? ifTrue : ifFalseImplementasi di Search.js:
js
getResults() {
$.getJSON(
universityData.root_url + "/wp-json/wp/v2/posts?search=" + this.searchField.val(),
(posts) => {
this.resultsDiv.html(`
<h2 class="search-overlay__section-title">General Information</h2>
${posts.length ? '<ul class="link-list min-list">' : '<p>No general information matches that search.</p>'}
${posts.map(item => `<li><a href="${item.link}">${item.title.rendered}</a></li>`).join('')}
${posts.length ? '</ul>' : ''}
`);
this.isSpinnerVisible = false;
}
);
}Penjelasan Ternary:
posts.length— jumlah item di array0= evaluates tofalse(tidak ada hasil)- Angka > 0 = evaluates to
true(ada hasil)
- Jika true: output
<ul>opening tag - Jika false: output
<p>No general information matches that search.</p> - Closing
</ul>juga perlu ternary agar tidak muncul kalau tidak ada hasil
Fix: isSpinnerVisible
Setelah HTML results ditampilkan, set this.isSpinnerVisible = false agar spinner hilang setelah data dimuat.
Membuat URL Fleksibel dengan wp_localize_script()
Masalah
URL hardcoded seperti http://localhost:3000/wp-json/... tidak akan bekerja di:
- Domain development lain
- Live server production
- WordPress yang di-install di subfolder
Solusi: wp_localize_script() di functions.php
php
// functions.php — di dalam function university_files()
wp_localize_script('main-university-js', 'universityData', array(
'root_url' => get_site_url()
));Penjelasan Parameter:
'main-university-js'— handle/nama dari script yang sudah di-enqueue'universityData'— nama variabel JavaScript yang akan dibuatarray(...)— data yang akan tersedia di JavaScript
Hasil di HTML Source:
html
<script>
var universityData = {"root_url":"https:\/\/fictional-university.local"};
</script>Penggunaan di JavaScript (Search.js):
js
// Ganti URL hardcoded:
// SEBELUM:
$.getJSON("http://localhost:3000/wp-json/wp/v2/posts?search=" + this.searchField.val(), ...);
// SESUDAH:
$.getJSON(universityData.root_url + "/wp-json/wp/v2/posts?search=" + this.searchField.val(), ...);Keuntungan:
get_site_url()otomatis mengembalikan URL WordPress saat ini- Bekerja di environment manapun (local, staging, production)
- Aman untuk distribusi theme ke banyak website
- Bisa tambah property lain ke array (misal:
'nonce','api_url', dll.)
Tip: Bisa Tambah Banyak Property
php
wp_localize_script('main-university-js', 'universityData', array(
'root_url' => get_site_url(),
'nonce' => wp_create_nonce('wp_rest'),
// property lainnya...
));