# Referensi Cepat WordPress

*Tema, hook, query, REST API, custom post type*

> Source: WordPress Developer Resources (developer.wordpress.org) · MIT

## Dasar Tema

### File yang Diperlukan

| Command | Description |
|---------|-------------|
| `style.css` | Header metadata tema + gaya |
| `index.php` | Template fallback (wajib) |
| `functions.php` | Pengaturan tema, hook, enqueue |
| `screenshot.png` | Pratinjau tema (1200x900) |

### Header style.css

```
/*
Theme Name: My Theme
Theme URI: https://example.com
Version: 1.0
Requires at least: 6.0
*/
```

### Pengaturan functions.php

```
add_action('after_setup_theme', function() {
    add_theme_support('title-tag');
    add_theme_support('post-thumbnails');
    add_theme_support('html5', ['search-form', 'gallery']);
    register_nav_menus(['primary' => 'Main Nav']);
});
```

## Hierarki Template

### Template Halaman

| Command | Description |
|---------|-------------|
| `front-page.php` | Halaman depan statis |
| `home.php` | Indeks posting blog |
| `single.php` | Posting tunggal |
| `page.php` | Halaman tunggal |
| `archive.php` | Arsip posting (tanggal, kategori) |
| `category.php` | Arsip kategori |
| `search.php` | Hasil pencarian |
| `404.php` | Tidak ditemukan |
| `index.php` | Fallback terakhir |

### Bagian Template

```
get_header();            // header.php
get_footer();            // footer.php
get_sidebar();           // sidebar.php
get_template_part('parts/card'); // parts/card.php
get_template_part('parts/card', 'featured');
```

### Urutan Pencarian (Posting Tunggal)

| Command | Description |
|---------|-------------|
| `1` | single-{post_type}-{slug}.php |
| `2` | single-{post_type}.php |
| `3` | single.php |
| `4` | singular.php |
| `5` | index.php |

## The Loop

### Loop Standar

```
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
  <h2><?php the_title(); ?></h2>
  <?php the_content(); ?>
<?php endwhile; endif; ?>
```

### Tag Template

| Command | Description |
|---------|-------------|
| `the_title()` | Cetak judul posting |
| `the_content()` | Cetak konten posting |
| `the_excerpt()` | Cetak ringkasan posting |
| `the_permalink()` | Cetak URL posting |
| `the_post_thumbnail()` | Cetak gambar unggulan |
| `the_date()` | Cetak tanggal terbit |
| `the_author()` | Cetak nama penulis |
| `the_category()` | Cetak tautan kategori |

### Getter (Mengembalikan, Bukan Mencetak)

```
$title = get_the_title();
$url   = get_permalink();
$id    = get_the_ID();
$thumb = get_the_post_thumbnail_url(null, 'medium');
```

## Custom Post Type

### Mendaftarkan CPT

```
add_action('init', function() {
    register_post_type('product', [
        'labels'  => ['name' => 'Products', 'singular_name' => 'Product'],
        'public'  => true,
        'has_archive' => true,
        'supports' => ['title', 'editor', 'thumbnail'],
    ]);
});
```

### Taksonomi Kustom

```
register_taxonomy('brand', 'product', [
    'labels'       => ['name' => 'Brands'],
    'hierarchical' => true,
    'rewrite'      => ['slug' => 'brand'],
]);
```

### Opsi Supports

| Command | Description |
|---------|-------------|
| `title` | Kolom judul posting |
| `editor` | Editor konten |
| `thumbnail` | Gambar unggulan |
| `excerpt` | Kolom ringkasan |
| `custom-fields` | Meta box untuk field kustom |
| `page-attributes` | Urutan menu, induk |
| `revisions` | Riwayat revisi |

## Hook dan Filter

### Action (Lakukan Sesuatu)

```
// Daftarkan hook
add_action('wp_head', 'my_analytics', 20);
function my_analytics() {
    echo '<script>/* tracking */</script>';
}
```

### Filter (Modifikasi Data)

```
// Ubah panjang ringkasan
add_filter('excerpt_length', fn() => 30);
// Tambahkan teks ke setiap posting
add_filter('the_content', function($c) {
    return is_single() ? $c . '<p>Terima kasih telah membaca!</p>' : $c;
});
```

### Hook Utama

| Command | Description |
|---------|-------------|
| `init` | WP terinisialisasi; daftarkan CPT di sini |
| `wp_enqueue_scripts` | Enqueue CSS/JS |
| `wp_head` | Output di <head> |
| `wp_footer` | Output sebelum </body> |
| `save_post` | Setelah posting disimpan |
| `pre_get_posts` | Modifikasi query utama sebelum eksekusi |
| `the_content` | Filter output konten posting |
| `the_title` | Filter output judul posting |

## WP_Query

### Query Kustom

```
$q = new WP_Query([
    'post_type'      => 'product',
    'posts_per_page' => 10,
    'orderby'        => 'date',
    'order'          => 'DESC',
]);
while ($q->have_posts()) : $q->the_post();
    the_title('<h3>', '</h3>');
endwhile; wp_reset_postdata();
```

### Parameter Umum

| Command | Description |
|---------|-------------|
| `post_type` | post, page, atau tipe kustom |
| `posts_per_page` | Jumlah hasil (-1 untuk semua) |
| `category_name` | Filter berdasarkan slug kategori |
| `tag` | Filter berdasarkan slug tag |
| `s` | Kata kunci pencarian |
| `meta_key / meta_value` | Filter berdasarkan field kustom |
| `tax_query` | Filter taksonomi tingkat lanjut |
| `date_query` | Filter berdasarkan rentang tanggal |

### Modifikasi Query Utama

```
add_action('pre_get_posts', function($q) {
    if (!is_admin() && $q->is_main_query() && is_home()) {
        $q->set('posts_per_page', 5);
    }
});
```

## REST API

### Endpoint Bawaan

| Command | Description |
|---------|-------------|
| `/wp-json/wp/v2/posts` | Daftar / buat posting |
| `/wp-json/wp/v2/posts/{id}` | Ambil / perbarui / hapus posting |
| `/wp-json/wp/v2/pages` | Endpoint halaman |
| `/wp-json/wp/v2/categories` | Endpoint kategori |
| `/wp-json/wp/v2/media` | Perpustakaan media |
| `/wp-json/wp/v2/users` | Endpoint pengguna |

### Endpoint Kustom

```
add_action('rest_api_init', function() {
    register_rest_route('myplugin/v1', '/items', [
        'methods'  => 'GET',
        'callback' => fn($req) => new WP_REST_Response(
            get_posts(['post_type' => 'item', 'numberposts' => 20])
        ),
        'permission_callback' => '__return_true',
    ]);
});
```

### Fetch dari JavaScript

```
const res = await fetch('/wp-json/wp/v2/posts?per_page=5');
const posts = await res.json();
posts.forEach(p => console.log(p.title.rendered));
```

## Fungsi

### Fungsi Posting

| Command | Description |
|---------|-------------|
| `get_posts($args)` | Ambil array posting |
| `wp_insert_post($arr)` | Buat atau perbarui posting |
| `wp_delete_post($id)` | Pindahkan ke sampah atau hapus posting |
| `get_post_meta($id, $key)` | Ambil nilai field kustom |
| `update_post_meta($id, $k, $v)` | Set nilai field kustom |

### Pengguna dan Autentikasi

| Command | Description |
|---------|-------------|
| `wp_get_current_user()` | Pengguna yang sedang login |
| `is_user_logged_in()` | Periksa status login |
| `current_user_can($cap)` | Periksa kemampuan |
| `wp_create_nonce($action)` | Buat nonce keamanan |
| `wp_verify_nonce($nonce, $a)` | Verifikasi nonce |

### Fungsi Utilitas

| Command | Description |
|---------|-------------|
| `esc_html($str)` | Escape untuk konteks HTML |
| `esc_attr($str)` | Escape untuk konteks atribut |
| `esc_url($url)` | Sanitasi URL |
| `wp_kses_post($html)` | Izinkan hanya HTML posting yang aman |
| `sanitize_text_field($s)` | Hapus tag dan spasi berlebih |
| `absint($val)` | Integer absolut |

## Enqueue

### Enqueue Gaya dan Script

```
add_action('wp_enqueue_scripts', function() {
    wp_enqueue_style('theme-style', get_stylesheet_uri(), [], '1.0');
    wp_enqueue_script('theme-js', get_theme_file_uri('/js/app.js'),
        ['jquery'], '1.0', true);
});
```

### Fungsi Enqueue

| Command | Description |
|---------|-------------|
| `wp_enqueue_style($h, $src)` | Daftarkan + enqueue CSS |
| `wp_enqueue_script($h, $src)` | Daftarkan + enqueue JS |
| `wp_localize_script($h, $n, $d)` | Kirim data PHP ke JS |
| `wp_dequeue_style($handle)` | Hapus gaya yang di-enqueue |
| `wp_dequeue_script($handle)` | Hapus script yang di-enqueue |

### Kirim Data ke JavaScript

```
wp_enqueue_script('my-app', get_theme_file_uri('/js/app.js'));
wp_localize_script('my-app', 'myData', [
    'ajaxUrl' => admin_url('admin-ajax.php'),
    'nonce'   => wp_create_nonce('my_action'),
]);
// JS: console.log(myData.ajaxUrl)
```

## Pola Umum

### Template Halaman Kustom

```
<?php
/* Template Name: Full Width */
get_header(); ?>
<main class="full-width">
  <?php the_content(); ?>
</main>
<?php get_footer(); ?>
```

### Handler AJAX

```
add_action('wp_ajax_my_action', 'handle_my_action');
add_action('wp_ajax_nopriv_my_action', 'handle_my_action');
function handle_my_action() {
    check_ajax_referer('my_action', 'nonce');
    wp_send_json_success(['msg' => 'OK']);
}
```

### Shortcode

```
add_shortcode('greeting', function($atts) {
    $a = shortcode_atts(['name' => 'World'], $atts);
    return '<p>Halo, ' . esc_html($a['name']) . '!</p>';
});
// Penggunaan: [greeting name="Zhi"]
```
