Testing HTML Markup, Code Highlighting, dan Block Styles

Postingan ini mendemonstrasikan berbagai markup HTML standar, syntax highlighting untuk kode, dan berbagai block styles WordPress.

Code Syntax Highlighting

Tema ini mendukung syntax highlighting dengan Prism.js untuk berbagai bahasa pemrograman. Aktifkan fitur ini di Customizer → Single Post → Enable Code Highlighting.

Gunakan komentar // lang: <nama bahasa coding> di atas kode untuk otomatis mendeteksi bahasa coding.

ruang iklan

HTML

// lang: html
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Halaman Contoh</title>
</head>
<body>
    <header class="site-header">
        <nav class="main-nav">
            <a href="/">Beranda</a>
            <a href="/about">Tentang</a>
            <a href="/contact">Kontak</a>
        </nav>
    </header>

    <main class="content">
        <article>
            <h1>Judul Artikel</h1>
            <p>Konten artikel di sini...</p>
        </article>
    </main>
</body>
</html>

CSS

// lang: css
/* CSS Custom Properties */
:root {
    --color-primary: #0f172a;
    --color-secondary: #64748b;
    --color-accent: #3b82f6;
    --spacing-unit: 1rem;
    --border-radius: 0.5rem;
}

/* Responsive Card Component */
.card {
    background: var(--color-surface);
    border-radius: var(--border-radius);
    padding: calc(var(--spacing-unit) * 1.5);
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
    transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.card:hover {
    transform: translateY(-2px);
    box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
}

.card__title {
    font-size: 1.25rem;
    font-weight: 600;
    margin-bottom: 0.5rem;
}

.card__description {
    color: var(--color-secondary);
    line-height: 1.6;
}

/* Media Query */
@media (min-width: 768px) {
    .card-grid {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: var(--spacing-unit);
    }
}

JavaScript

// lang: javascript
// Modern JavaScript ES6+ Example
class ThemeToggle {
    constructor(buttonSelector) {
        this.button = document.querySelector(buttonSelector);
        this.currentTheme = localStorage.getItem('theme') || 'light';
        this.init();
    }

    init() {
        // Set initial theme
        document.documentElement.setAttribute('data-theme', this.currentTheme);

        // Add event listener
        this.button?.addEventListener('click', () => this.toggle());
    }

    toggle() {
        this.currentTheme = this.currentTheme === 'light' ? 'dark' : 'light';
        document.documentElement.setAttribute('data-theme', this.currentTheme);
        localStorage.setItem('theme', this.currentTheme);

        // Dispatch custom event
        window.dispatchEvent(new CustomEvent('themeChange', {
            detail: { theme: this.currentTheme }
        }));
    }
}

// Initialize
document.addEventListener('DOMContentLoaded', () => {
    const toggle = new ThemeToggle('.theme-toggle-btn');
});

// Async/Await Example
async function fetchPosts(page = 1) {
    try {
        const response = await fetch(`/wp-json/wp/v2/posts?page=${page}`);

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        const posts = await response.json();
        return posts.map(post => ({
            id: post.id,
            title: post.title.rendered,
            excerpt: post.excerpt.rendered
        }));
    } catch (error) {
        console.error('Failed to fetch posts:', error);
        return [];
    }
}

Python

# lang: python
from dataclasses import dataclass
from typing import List, Optional
import asyncio
import aiohttp

@dataclass
class Article:
    """Represents a blog article."""
    id: int
    title: str
    content: str
    author: str
    tags: List[str]
    published: bool = False

class BlogAPI:
    """Async blog API client."""

    def __init__(self, base_url: str):
        self.base_url = base_url
        self.session: Optional[aiohttp.ClientSession] = None

    async def __aenter__(self):
        self.session = aiohttp.ClientSession()
        return self

    async def __aexit__(self, *args):
        await self.session.close()

    async def get_articles(self, limit: int = 10) -> List[Article]:
        """Fetch articles from the API."""
        async with self.session.get(
            f"{self.base_url}/articles",
            params={"limit": limit}
        ) as response:
            data = await response.json()
            return [Article(**item) for item in data]

    async def create_article(self, article: Article) -> dict:
        """Create a new article."""
        async with self.session.post(
            f"{self.base_url}/articles",
            json=article.__dict__
        ) as response:
            return await response.json()

# Usage example
async def main():
    async with BlogAPI("https://api.example.com") as api:
        articles = await api.get_articles(limit=5)
        for article in articles:
            print(f"📝 {article.title} by {article.author}")

if __name__ == "__main__":
    asyncio.run(main())

PHP

// lang: php
<?php
/**
 * Custom WordPress Query Example
 *
 * @package MyTheme
 */

declare(strict_types=1);

namespace MyTheme\Query;

class PostQuery {
    private array $args;
    private ?\WP_Query $query = null;

    public function __construct(array $args = []) {
        $this->args = wp_parse_args($args, [
            'post_type'      => 'post',
            'posts_per_page' => 10,
            'post_status'    => 'publish',
            'orderby'        => 'date',
            'order'          => 'DESC',
        ]);
    }

    public function byCategory(string $category): self {
        $this->args['category_name'] = sanitize_text_field($category);
        return $this;
    }

    public function byTag(string $tag): self {
        $this->args['tag'] = sanitize_text_field($tag);
        return $this;
    }

    public function limit(int $count): self {
        $this->args['posts_per_page'] = absint($count);
        return $this;
    }

    public function execute(): \WP_Query {
        $this->query = new \WP_Query($this->args);
        return $this->query;
    }

    public function getPosts(): array {
        if (!$this->query) {
            $this->execute();
        }

        return array_map(function($post) {
            return [
                'id'        => $post->ID,
                'title'     => get_the_title($post),
                'excerpt'   => get_the_excerpt($post),
                'permalink' => get_permalink($post),
                'thumbnail' => get_the_post_thumbnail_url($post, 'medium'),
            ];
        }, $this->query->posts);
    }
}

// Usage
$posts = (new PostQuery())
    ->byCategory('tutorial')
    ->limit(5)
    ->getPosts();

foreach ($posts as $post) {
    printf(
        '<article><h2>%s</h2><p>%s</p></article>',
        esc_html($post['title']),
        wp_kses_post($post['excerpt'])
    );
}

Bash / Shell

# lang: bash
#!/bin/bash

# WordPress Development Script
# Automates common development tasks

set -e  # Exit on error

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Configuration
THEME_DIR="wp-content/themes/mytheme"
BUILD_DIR="build"

log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Build theme assets
build_assets() {
    log_info "Building theme assets..."

    cd "$THEME_DIR" || exit 1

    if [ -f "package.json" ]; then
        npm install
        npm run build
        log_info "Assets built successfully!"
    else
        log_error "package.json not found!"
        exit 1
    fi
}

# Create distribution ZIP
create_dist() {
    log_info "Creating distribution package..."

    local version=$(grep -oP '"version":\s*"\K[^"]+' package.json)
    local zip_name="mytheme-${version}.zip"

    mkdir -p "$BUILD_DIR"
    zip -r "$BUILD_DIR/$zip_name" . \
        -x "node_modules/*" \
        -x ".git/*" \
        -x "*.map" \
        -x ".env"

    log_info "Created: $BUILD_DIR/$zip_name"
}

# Main
case "$1" in
    build)
        build_assets
        ;;
    dist)
        build_assets
        create_dist
        ;;
    *)
        echo "Usage: $0 {build|dist}"
        exit 1
        ;;
esac

SQL

-- lang: sql
-- WordPress Database Queries Example

-- Get popular posts by comment count
SELECT
    p.ID,
    p.post_title,
    p.post_date,
    COUNT(c.comment_ID) as comment_count,
    u.display_name as author_name
FROM wp_posts p
LEFT JOIN wp_comments c ON p.ID = c.comment_post_ID
    AND c.comment_approved = '1'
LEFT JOIN wp_users u ON p.post_author = u.ID
WHERE p.post_type = 'post'
    AND p.post_status = 'publish'
GROUP BY p.ID
ORDER BY comment_count DESC
LIMIT 10;

-- Get posts with specific meta value
SELECT
    p.ID,
    p.post_title,
    pm.meta_value as featured
FROM wp_posts p
INNER JOIN wp_postmeta pm ON p.ID = pm.post_id
WHERE pm.meta_key = '_is_featured'
    AND pm.meta_value = '1'
    AND p.post_status = 'publish'
ORDER BY p.post_date DESC;

-- Create custom table for analytics
CREATE TABLE IF NOT EXISTS wp_post_views (
    id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
    post_id BIGINT(20) UNSIGNED NOT NULL,
    view_date DATE NOT NULL,
    view_count INT(11) DEFAULT 0,
    PRIMARY KEY (id),
    UNIQUE KEY post_date_unique (post_id, view_date),
    KEY post_id_idx (post_id),
    FOREIGN KEY (post_id) REFERENCES wp_posts(ID) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

JSON

// lang: json
{
    "name": "sastrapro-theme",
    "version": "1.0.0",
    "description": "Modern WordPress theme with Vite build system",
    "scripts": {
        "dev": "vite build --watch",
        "build": "vite build",
        "serve": "browser-sync start --proxy 'localhost' --files 'assets/dist/**/*'"
    },
    "devDependencies": {
        "autoprefixer": "^10.4.16",
        "browser-sync": "^2.29.3",
        "postcss": "^8.4.31",
        "sass": "^1.69.5",
        "vite": "^5.0.0"
    },
    "browserslist": [
        "> 1%",
        "last 2 versions",
        "not dead"
    ],
    "theme": {
        "colors": {
            "primary": "#0f172a",
            "secondary": "#64748b",
            "accent": "#3b82f6"
        },
        "breakpoints": {
            "sm": "576px",
            "md": "768px",
            "lg": "1024px",
            "xl": "1280px"
        }
    }
}

WordPress Block Styles

Tema SastraPro menyediakan beberapa custom block styles untuk mempercantik tampilan konten Anda.

Button Styles

Default Button:

Outline Button Style:

Quote Styles

Default Quote:

Kesederhanaan adalah kecanggihan tertinggi. Desain yang baik adalah desain yang tidak terlihat.

Leonardo da Vinci

Border Accent Quote Style:

Kode yang baik adalah dokumentasi terbaik. Saat kamu hendak menambahkan komentar, tanyakan pada dirimu: “Bagaimana cara memperbaiki kode ini agar komentar tidak diperlukan?”

Steve McConnell

List Styles

Default Unordered List:

  • Responsive design untuk semua perangkat
  • Dark mode dengan toggle otomatis
  • SEO-friendly dengan schema markup
  • Performa optimal dengan lazy loading

Default Ordered List:

  1. Install tema melalui WordPress admin
  2. Aktifkan tema di Appearance → Themes
  3. Konfigurasi pengaturan di Customizer
  4. Mulai membuat konten!

No Bullets List Style:

  • ✅ Fitur lengkap tanpa plugin tambahan
  • ✅ Update gratis seumur hidup
  • ✅ Dokumentasi lengkap
  • ✅ Support prioritas

Group Card Style

Informasi Penting

Ini adalah contoh Group block dengan style “Card”. Sangat berguna untuk menampilkan informasi yang perlu ditonjolkan atau membuat callout box.

Anda dapat memasukkan berbagai jenis konten di dalam card ini, termasuk list, gambar, dan block lainnya.

Table Block

FiturFree ThemeSastraPro
Dark Mode
Code Highlighting
Table of Contents
Related PostsBasicAdvanced
SEO FeaturesBasicComplete
Auto Updates

HTML Typography & Markup

Headings

Heading 1 – Judul Utama

Heading 2 – Sub Judul

Heading 3 – Bagian

Heading 4 – Sub Bagian

Heading 5 – Detail
Heading 6 – Micro Heading

Text Formatting

Ini adalah paragraf standar dengan berbagai format teks. Anda dapat menggunakan teks tebal untuk penekanan kuat, teks miring untuk penekanan ringan, atau kombinasi tebal dan miring.

Untuk kode inline, gunakan format seperti ini. Sangat berguna untuk menyebutkan nama fungsi seperti get_template_part() atau variabel $post_id.

Anda juga dapat menambahkan link seperti ini atau highlight teks penting untuk menarik perhatian pembaca.

Untuk konten yang dihapus gunakan strikethrough seperti ini, dan untuk subscript/superscript: H2O atau E=mc2.

Preformatted Text

Ini adalah preformatted text.
Spasi dan line breaks
    dipertahankan persis
        seperti yang ditulis.

Berguna untuk ASCII art atau teks terstruktur.

Pullquote

Pullquote digunakan untuk menyoroti kutipan penting dari artikel. Biasanya ditampilkan lebih besar dan menonjol dari teks biasa.

Penulis Terkenal

Details/Accordion

Klik untuk melihat lebih banyak informasi

Ini adalah konten tersembunyi yang akan muncul ketika pengguna mengklik summary. Sangat berguna untuk FAQ atau konten yang tidak perlu ditampilkan secara langsung.

Bagaimana cara menggunakan tema ini?

Upload tema melalui WordPress admin di Appearance → Themes → Add New → Upload Theme. Setelah diupload, aktifkan tema dan konfigurasi melalui Customizer.

Apakah tema ini kompatibel dengan plugin populer?

Ya! Tema ini kompatibel dengan WooCommerce, Contact Form 7, Yoast SEO, dan plugin populer lainnya. Kami menguji kompatibilitas secara berkala.

Footnotes

WordPress mendukung footnotes untuk referensi akademis atau penjelasan tambahan. Fitur ini berguna untuk artikel yang membutuhkan sitasi atau catatan kaki.


Media Blocks

Image dengan Caption

Contoh gambar coding
Contoh gambar dengan caption. Foto dari Unsplash.

Video Embed

Contoh embed video YouTube

Columns Layout

Kolom Pertama

Konten kolom pertama. WordPress Columns block memudahkan pembuatan layout multi-kolom tanpa perlu kode CSS khusus.

Kolom Kedua

Konten kolom kedua. Layout ini responsif dan akan menyesuaikan secara otomatis pada layar mobile.

Kolom Ketiga

Konten kolom ketiga. Anda dapat mengubah proporsi kolom sesuai kebutuhan desain.


Mas Sugeng

Pembuat tema blogger dan tema wordpress Indonesia.

ruang iklan