Lewati ke konten

Membangun Pustaka Blok

Pustaka blok adalah kumpulan blok bagian mandiri yang disusun menjadi halaman lengkap. Setiap blok memiliki skema, templat, dan gayanya sendiri. Blockstudio menyediakan kerangka kerja: pemrosesan Tailwind CSS, pendaftaran atribut, dan sinkronisasi halaman. Anda menyediakan bloknya.

Panduan ini membahas cara membangun pustaka dari awal, mengikuti arsitektur yang sama dengan yang digunakan di ratusan tema produksi. Pada akhirnya, Anda akan memiliki tema yang berfungsi dengan hero, kisi fitur, dan halaman beranda yang tersusun.

Struktur Folder

Setiap tema Blockstudio mengikuti tata letak yang sama:

Kode
my-theme/
├── style.css                           # WordPress header + Tailwind v4 config
├── blockstudio.json                    # Blockstudio settings
├── functions.php                       # Section helper + Tailwind filter
├── index.php                           # Main WordPress template
├── blockstudio/
│   ├── fields/
│   │   └── section/
│   │       └── field.json              # Shared section controls
│   └── sections/
│       ├── hero/
│       │   ├── block.json
│       │   └── index.php
│       └── features/
│           ├── block.json
│           └── index.php
└── pages/
    └── home/
        ├── page.json
        └── index.php

Blok berada di blockstudio/sections/. Setiap blok berupa folder dengan skema block.json dan templat index.php. Halaman berada di pages/ dan menyusun blok menggunakan sintaks <block>.

Berkas Fondasi

blockstudio.json

Berkas ini mengonfigurasi cara Blockstudio memproses tema Anda. Konfigurasinya sama untuk setiap tema:

JSON
{
	"assets": {
		"enqueue": true,
		"reset": {
			"enabled": true,
			"fullWidth": ["page"]
		},
		"minify": { "css": true, "js": true },
		"process": { "scss": false, "scssFiles": true }
	},
	"tailwind": {
		"enabled": true,
		"config": ""
	},
	"dev": {
		"canvas": { "enabled": true }
	},
	"$schema": "https://blockstudio.dev/schema/blockstudio"
}

reset menghapus gaya blok WordPress bawaan. fullWidth membuat jenis pos page membentang selebar penuh. canvas mengaktifkan mode kanvas editor untuk pengalaman penyuntingan yang lebih bersih.

Kolom tailwind.config sengaja dibiarkan kosong. Dengan Tailwind v4, semua konfigurasi berada di style.css menggunakan pendekatan yang mengutamakan CSS.

index.php

Templat utama WordPress. Ini WordPress standar, tidak khusus untuk Blockstudio:

PHP
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
	<meta charset="<?php bloginfo( 'charset' ); ?>">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<?php wp_head(); ?>
</head>
<body <?php body_class(); ?>>
<?php wp_body_open(); ?>

<main>
<?php
if ( have_posts() ) {
	while ( have_posts() ) {
		the_post();
		the_content();
	}
}
?>
</main>

<?php wp_footer(); ?>
</body>
</html>

Tambahkan header.php dan footer.php saat Anda memerlukan navigasi. Untuk saat ini, templat minimal sudah cukup untuk merender blok.

Token Desain

Semua pengaturan tema dilakukan di style.css menggunakan direktif Tailwind v4 @theme. Inilah inti sistem desain Anda.

CSS
/*
Theme Name: My Theme
Theme URI: https://example.com
Description: A clean theme built with Blockstudio.
Version: 1.0.0
Requires at least: 6.0
Requires PHP: 8.2
Author: Your Name
Text Domain: my-theme
*/

@theme {
	--font-sans: 'Inter', ui-sans-serif, system-ui, sans-serif;
	--color-bg: #050505;
	--color-elevated: #111111;
	--color-subtle: rgb(255 255 255 / 0.06);
	--color-muted: #888888;
	--color-accent: #6366f1;
	--color-accent-hover: #4f46e5;
}

Setiap tema setidaknya memerlukan:

Token Kegunaan
--font-sans atau --font-serif Jenis huruf utama
--color-bg Latar halaman
--color-elevated Latar kartu/permukaan
--color-subtle Garis tepi, pemisah
--color-muted Teks sekunder
--color-accent Warna merek utama

Token ini otomatis menghasilkan utilitas Tailwind. --color-accent menjadi bg-accent, text-accent, border-accent, dan seterusnya.

Untuk tema terang, balik nilainya:

CSS
@theme {
	--font-serif: 'Zilla Slab', serif;
	--font-sans: 'DM Sans', sans-serif;
	--color-bg: #f5f0e8;
	--color-elevated: #ece6da;
	--color-heading: #2c1810;
	--color-body: #6b5c4f;
	--color-muted: #9a8b7d;
	--color-accent: #2d5016;
	--color-subtle: #d9d1c4;
}

Gaya Dasar dan Utilitas

Di bawah blok @theme, tambahkan gaya body, nilai bawaan lapisan dasar, dan utilitas khusus.

Gaya body harus berada di luar @layer agar editor WordPress dapat menggunakannya:

CSS
body {
	@apply bg-bg font-sans text-white antialiased;
}

Lapisan dasar untuk nilai bawaan elemen:

CSS
@layer base {
	section {
		@apply relative overflow-hidden;
	}

	h1, h2, h3 {
		text-wrap: balance;
	}

	p {
		text-wrap: pretty;
	}
}

Utilitas khusus untuk pola yang dapat digunakan kembali. Setiap tema mendefinisikan utilitas container untuk jarak antarbagian yang konsisten, serta biasanya card, badge, dan utilitas tombol:

CSS
@utility container-px {
	@apply mx-auto max-w-5xl px-6;
}

@utility container {
	@apply container-px py-24 sm:py-32;
}

@utility container-no-pb {
	@apply pb-0 sm:pb-0;
}

@utility card {
	@apply rounded-2xl border border-subtle bg-elevated/80 p-8 transition-all duration-300;

	&:hover {
		border-color: rgb(255 255 255 / 0.1);
	}
}

@utility badge {
	@apply inline-flex items-center gap-2 rounded-full border border-subtle bg-white/5 px-3.5 py-1.5 text-sm text-muted;
}

@utility btn-primary {
	@apply inline-flex items-center gap-2 rounded-full bg-accent px-6 py-3 text-sm font-medium text-white transition-colors;

	&:hover {
		@apply bg-accent-hover;
	}
}

@utility btn-secondary {
	@apply inline-flex items-center gap-2 rounded-full border border-subtle px-6 py-3 text-sm font-medium text-white transition-all;

	&:hover {
		border-color: rgb(255 255 255 / 0.15);
		background: rgb(255 255 255 / 0.04);
	}
}

Pemilih pseudo ditempatkan di dalam blok @utility menggunakan nesting CSS (&:hover). Jangan pernah menaruhnya di nama utilitas. @utility btn-primary:hover {} tidak valid dan akan ditolak oleh Tailwind.

@source sebaris

Blockstudio memindai templat blok Anda secara otomatis untuk menemukan kelas Tailwind. Namun, kelas yang digunakan di luar templat blok (di functions.php, header.php, index.php) tidak dipindai. Deklarasikan kelas tersebut dengan @source inline:

CSS
@source inline("bg-bg bg-accent-tint container container-px container-no-pb");

Ini memberi tahu Tailwind untuk menyertakan kelas-kelas tersebut dalam keluaran, meskipun kelas itu hanya muncul di berkas PHP yang tidak dipindai.

Pola Bagian

Pola bagian adalah konvensi terpenting dalam pustaka blok Blockstudio. Pola ini memberikan jarak yang konsisten, pergantian latar, dan kendali padding pada setiap blok melalui dua mekanisme bersama: kolom khusus dan helper PHP.

Kolom Bagian

Buat definisi kolom bersama yang dapat dirujuk oleh setiap blok:

JSON
{
	"$schema": "https://blockstudio.dev/schema/field",
	"name": "section",
	"title": "Section",
	"attributes": [
		{
			"type": "group",
			"attributes": [
				{
					"id": "removeBottomPadding",
					"type": "toggle",
					"label": "Remove bottom padding"
				},
				{
					"id": "accentBg",
					"type": "toggle",
					"label": "Accent background"
				}
			]
		}
	]
}

Kolom ini muncul di inspektur setiap blok pada tab “Section”. Klien mendapatkan dua kontrol: mengaktifkan latar aksen dan menghapus padding bawah (berguna untuk menumpuk bagian tanpa celah).

Helper Bagian

Di functions.php, buat helper yang mengubah atribut ini menjadi kelas CSS:

PHP
<?php
/**
 * My Theme functions.
 *
 * @package My_Theme
 */

/**
 * Returns section and container class strings based on block attributes.
 *
 * @param array  $a               Block attributes.
 * @param string $extra_section   Additional classes for the section element.
 * @param string $extra_container Additional classes for the container element.
 * @return array Array of [ section_classes, container_classes ].
 */
function mytheme_section_classes( array $a, string $extra_section = '', string $extra_container = '' ): array {
	$section   = ! empty( $a['accentBg'] ) ? 'bg-accent-tint' : 'bg-bg';
	$container = 'container';

	if ( ! empty( $a['removeBottomPadding'] ) ) {
		$container .= ' container-no-pb';
	}

	if ( $extra_section ) {
		$section .= ' ' . $extra_section;
	}

	if ( $extra_container ) {
		$container .= ' ' . $extra_container;
	}

	return array( $section, $container );
}

Setiap templat blok memanggil helper ini sebagai baris pertamanya. Helper mengembalikan dua string kelas: satu untuk elemen <section> luar dan satu untuk kontainer <div> dalam.

Filter Konfigurasi Tailwind

Di functions.php juga, tambahkan filter yang meneruskan style.css Anda ke pemroses Tailwind milik Blockstudio:

PHP
add_filter(
	'blockstudio/settings/tailwind/config',
	function () {
		$style = get_stylesheet_directory() . '/style.css';

		if ( file_exists( $style ) ) {
			// phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- Reading local theme file.
			return file_get_contents( $style );
		}

		return '';
	}
);

Ini memberi tahu Blockstudio agar menggunakan style.css Anda sebagai sumber konfigurasi Tailwind v4. Tanpanya, token @theme dan definisi @utility Anda tidak akan tersedia di templat blok.

Blok Pertama Anda: Hero

Bagian hero menunjukkan pola blok secara lengkap. Mulailah dengan skemanya:

JSON
{
	"$schema": "https://blockstudio.dev/schema/block",
	"name": "my-theme/hero",
	"title": "Hero",
	"category": "my-theme",
	"icon": "star-filled",
	"description": "Full-width hero section with heading, description, and buttons.",
	"blockstudio": {
		"attributes": [
			{
				"type": "tabs",
				"tabs": [
					{
						"title": "Content",
						"attributes": [
							{
								"type": "group",
								"attributes": [
									{
										"id": "heading",
										"type": "text",
										"label": "Heading",
										"default": "Build beautiful websites without the complexity"
									},
									{
										"id": "description",
										"type": "textarea",
										"label": "Description",
										"default": "A powerful framework that lets you create stunning designs using the WordPress editor."
									}
								]
							},
							{
								"type": "group",
								"attributes": [
									{
										"id": "primaryButton",
										"type": "link",
										"label": "Primary Button",
										"default": {
											"title": "Get Started",
											"url": "#"
										}
									},
									{
										"id": "secondaryButton",
										"type": "link",
										"label": "Secondary Button",
										"default": {
											"title": "Learn More",
											"url": "#"
										}
									}
								]
							}
						]
					},
					{
						"title": "Section",
						"attributes": [
							{ "type": "custom/section" }
						]
					}
				]
			}
		]
	}
}

Pola penting yang perlu diperhatikan:

Pembungkus tabs membuat inspektur dengan dua tab: “Content” untuk kolom blok dan “Section” untuk kontrol bagian bersama. Semua blok menggunakan struktur ini.

Kolom diatur dalam kontainer group. Grup memisahkan kolom terkait secara visual di inspektur. Grup pertama menampung kolom teks, sedangkan grup kedua menampung kolom tautan.

Nilai bawaan menyediakan konten yang bermakna sehingga blok terlihat lengkap begitu disisipkan. Ini sangat penting untuk penyusunan halaman, ketika blok ditambahkan tanpa interaksi pengguna.

Sekarang, templatnya:

PHP
<?php list( $section_classes, $container_classes ) = mytheme_section_classes( $a, '', 'text-center' ); ?>

<section useBlockProps class="<?php echo esc_attr( $section_classes ); ?>">
	<div class="<?php echo esc_attr( $container_classes ); ?>">
		<h1 class="text-5xl font-medium tracking-tight sm:text-6xl lg:text-7xl">
			<?php echo esc_html( $a['heading'] ); ?>
		</h1>

		<?php if ( ! empty( $a['description'] ) ) : ?>
			<p class="mt-6 text-lg leading-relaxed text-muted max-w-xl mx-auto">
				<?php echo esc_html( $a['description'] ); ?>
			</p>
		<?php endif; ?>

		<div class="mt-10 flex items-center justify-center gap-x-4">
			<?php if ( ! empty( $a['primaryButton']['url'] ) ) : ?>
				<a href="<?php echo esc_url( $a['primaryButton']['url'] ); ?>" class="btn-primary">
					<?php echo esc_html( $a['primaryButton']['title'] ); ?>
				</a>
			<?php endif; ?>

			<?php if ( ! empty( $a['secondaryButton']['url'] ) ) : ?>
				<a href="<?php echo esc_url( $a['secondaryButton']['url'] ); ?>" class="btn-secondary">
					<?php echo esc_html( $a['secondaryButton']['title'] ); ?>
				</a>
			<?php endif; ?>
		</div>
	</div>
</section>

Templat mengikuti pola yang konsisten:

  1. Panggil helper bagian untuk mendapatkan kelas CSS
  2. <section> luar dengan useBlockProps dan kelas bagian
  3. <div> dalam dengan kelas kontainer
  4. Konten dirender dari $a (singkatan untuk atribut)
  5. Perenderan kondisional untuk kolom opsional
  6. Escaping yang tepat: esc_html() untuk teks, esc_url() untuk URL, esc_attr() untuk atribut

Menambahkan Repeater: Kisi Fitur

Repeater memungkinkan klien menambah, menghapus, dan mengurutkan ulang item. Kisi fitur adalah contoh klasik:

JSON
{
	"$schema": "https://blockstudio.dev/schema/block",
	"name": "my-theme/features",
	"title": "Features",
	"category": "my-theme",
	"icon": "grid-view",
	"description": "Feature grid with titles and descriptions.",
	"blockstudio": {
		"attributes": [
			{
				"type": "tabs",
				"tabs": [
					{
						"title": "Content",
						"attributes": [
							{
								"type": "group",
								"attributes": [
									{
										"id": "heading",
										"type": "text",
										"label": "Heading",
										"default": "Everything you need"
									},
									{
										"id": "description",
										"type": "textarea",
										"label": "Description",
										"default": "Our toolkit gives you the building blocks to go from idea to production."
									}
								]
							},
							{
								"type": "group",
								"attributes": [
									{
										"id": "features",
										"type": "repeater",
										"label": "Features",
										"textMinimized": {
											"id": "title",
											"fallback": "Feature"
										},
										"default": [
											{
												"title": "Lightning Fast",
												"description": "Optimized for performance with minimal overhead."
											},
											{
												"title": "Fully Responsive",
												"description": "Every component adapts across all screen sizes."
											},
											{
												"title": "Easy to Customize",
												"description": "Adjust every detail to match your brand."
											}
										],
										"attributes": [
											{
												"id": "title",
												"type": "text",
												"label": "Title"
											},
											{
												"id": "description",
												"type": "textarea",
												"label": "Description"
											}
										]
									}
								]
							}
						]
					},
					{
						"title": "Section",
						"attributes": [
							{ "type": "custom/section" }
						]
					}
				]
			}
		]
	}
}

Properti textMinimized mengatur teks yang ditampilkan saat baris repeater diciutkan. Properti ini membaca nilai kolom title, dan jika kosong akan menggunakan “Feature”. Ini membuat inspektur tetap mudah digunakan saat memiliki banyak item.

Array default menyediakan item awal. Item ini muncul saat blok pertama kali disisipkan. Selalu berikan nilai bawaan yang realistis agar blok langsung terlihat lengkap.

PHP
<?php list( $section_classes, $container_classes ) = mytheme_section_classes( $a ); ?>

<section useBlockProps class="<?php echo esc_attr( $section_classes ); ?>">
	<div class="<?php echo esc_attr( $container_classes ); ?>">
		<?php if ( ! empty( $a['heading'] ) ) : ?>
			<div class="text-center max-w-2xl mx-auto">
				<h2 class="text-3xl font-medium tracking-tight sm:text-4xl">
					<?php echo esc_html( $a['heading'] ); ?>
				</h2>

				<?php if ( ! empty( $a['description'] ) ) : ?>
					<p class="mt-4 text-base leading-relaxed text-muted">
						<?php echo esc_html( $a['description'] ); ?>
					</p>
				<?php endif; ?>
			</div>
		<?php endif; ?>

		<?php if ( ! empty( $a['features'] ) ) : ?>
			<div class="mt-16 grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
				<?php foreach ( $a['features'] as $feature ) : ?>
					<div class="card">
						<h3 class="text-sm font-medium">
							<?php echo esc_html( $feature['title'] ); ?>
						</h3>
						<p class="mt-2 text-sm leading-relaxed text-muted">
							<?php echo esc_html( $feature['description'] ); ?>
						</p>
					</div>
				<?php endforeach; ?>
			</div>
		<?php endif; ?>
	</div>
</section>

Item repeater diakses sebagai array PHP biasa. Lakukan iterasi dengan foreach, lalu akses kolom setiap item melalui id-nya.

Gambar dan Placeholder

Untuk blok dengan gambar, gunakan jenis kolom files dan komponen MediaPlaceholder. Placeholder menampilkan area seret dan lepas di editor:

JSON
{
	"id": "image",
	"type": "files",
	"label": "Image"
}

Di templat, render gambar dengan wp_get_attachment_image() dan tampilkan SVG placeholder saat belum ada gambar yang dipilih:

PHP
<div class="overflow-hidden rounded-2xl bg-elevated">
	<MediaPlaceholder attribute="image" allowedTypes="<?php echo esc_attr( wp_json_encode( array( 'image' ) ) ); ?>" />
	<?php if ( ! empty( $a['image'] ) ) : ?>
		<?php echo wp_get_attachment_image( $a['image'][0]['ID'], 'full', false, array( 'class' => 'block w-full' ) ); ?>
	<?php else : ?>
		<?php echo blockstudio_placeholder_dark(); ?>
	<?php endif; ?>
</div>

blockstudio_placeholder_dark() mengembalikan SVG sebaris yang menggunakan currentColor dengan variabel --color-accent, sehingga otomatis menyesuaikan tema Anda. Untuk tema terang, gunakan blockstudio_placeholder_light(). Keduanya menerima argumen varian:

PHP
blockstudio_placeholder_dark( 'dashboard' )  // Dashboard mockup
blockstudio_placeholder_dark( 'chart' )      // Chart illustration
blockstudio_placeholder_dark( 'product' )    // Product shot

Menyusun Halaman

Halaman menyusun blok menjadi tata letak lengkap menggunakan sintaks <block>. Buat halaman beranda:

JSON
{
	"name": "home",
	"title": "Home",
	"slug": "home",
	"postType": "page",
	"postStatus": "publish",
	"templateLock": "all"
}
PHP
<block name="my-theme/hero"></block>
<block name="my-theme/features"></block>

Selesai. Setiap elemen <block> menyisipkan blok dengan nilai atribut bawaannya. Jalankan wp bs pages sync untuk menerapkan sumber halaman ke WordPress.

Untuk mengganti nilai bawaan pada halaman tertentu, teruskan atribut secara langsung:

PHP
<block name="my-theme/hero" heading="About Us" description="Our story and mission."></block>
<block name="my-theme/features" heading="Our Values"></block>

Dengan templateLock disetel ke "all", klien tidak dapat menambah, menghapus, atau mengatur ulang blok. Struktur halaman dikunci sesuai templat Anda. Lihat Pages untuk mode penguncian dan kontrol penyuntingan lainnya.

Mengembangkan Pustaka

Pustaka minimal dimulai dengan 3-5 blok. Pustaka lengkap memiliki 8-14 blok. Berikut jenis blok yang umum, diurutkan secara kasar berdasarkan frekuensi kemunculannya:

Blok Deskripsi Kolom Utama
Hero Judul besar dengan CTA heading, description, links
Features Kisi manfaat heading, repeater with title + description
CTA Banner ajakan bertindak heading, description, link
Pricing Perbandingan paket heading, repeater with name + price + features
Testimonials Kutipan pelanggan repeater with quote + name + role
FAQ Akordeon pertanyaan heading, repeater with question + answer
Logos Kumpulan logo klien heading (logos are typically hardcoded SVGs)
Content Baris teks + gambar yang berselang-seling repeater with heading + description + image
Showcase Gambar selebar penuh dengan keterangan heading, description, image
Team Kisi anggota tim heading, repeater with name + role + image
Stats Metrik utama repeater with number + label

Setiap blok mengikuti pola yang sama: tab (Content + Section), grup untuk pengaturan, repeater untuk daftar, dan helper bagian untuk jarak yang konsisten. Setelah Anda membangun dua atau tiga blok, menambahkan blok lainnya menjadi pekerjaan mekanis.

Menambahkan Halaman Lain

Seiring bertambahnya pustaka, susun halaman berbeda dari blok yang sama:

PHP
<block name="my-theme/hero" heading="Simple, Transparent Pricing" description="Choose the plan that fits."></block>
<block name="my-theme/pricing"></block>
<block name="my-theme/faq" heading="Pricing FAQ"></block>
<block name="my-theme/cta"></block>
PHP
<block name="my-theme/hero" heading="About Us" description="Our story."></block>
<block name="my-theme/team"></block>
<block name="my-theme/testimonials"></block>
<block name="my-theme/cta" heading="Join Our Team"></block>

Blok yang sama dapat digunakan di beberapa halaman, masing-masing dengan nilai bawaan berbeda. Inilah keunggulan pendekatan pustaka: bangun blok sekali, lalu susun menjadi sebanyak mungkin halaman yang Anda perlukan.

Langkah Berikutnya