0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

WordPressのブロックパターンが更新されない?キャッシュを回避して即反映する方法

Posted at

WordPress 6.x 以降、テーマの patterns/ ディレクトリに PHP ファイルを追加すると、ブロックパターンとして自動的に読み込まれます。
しかし開発中に patterns/cta.php などを編集しても、管理画面のパターン一覧にすぐ反映されず、反映が遅いという現象が起こります。

解決方法 1: Local のキャッシュをクリア

Local (by Flywheel) を使っている場合、キャッシュが効いている可能性があります。

  • サイトを Stop → Start で再起動
    スクリーンショット 2025-09-15 21.29.41.png
    スクリーンショット 2025-09-15 21.29.47.png

  • WP-CLI が使える場合は
    ※使えない場合はLocalのSite shellからterminalを開いてください。
    スクリーンショット 2025-09-15 21.30.43.png
    スクリーンショット 2025-09-15 21.32.35.png

wp cache flush

を実行。これで反映されることもありますが、毎回は面倒です。

解決方法 2: functions.php から直接登録する

開発中におすすめなのは、WordPress の自動スキャンに頼らず 自分でパターンを登録する方法です。
file_get_contents() で patterns/*.php を直接読み込めば、保存した瞬間に反映されます。

実装例

function mytheme_block_patterns() {

	// 独自カテゴリを追加
	register_block_pattern_category(
		'mytheme',
		array( 'label' => 'My Theme' )
	);

	// デフォルトのコアパターンを削除(不要なら)
	remove_theme_support('core-block-patterns');

	// 登録するパターン一覧
	$patterns = array(
		'cta'                => 'CTAセクション',
		'gallery'            => 'ギャラリー',
		'frame'              => '見出し付きの囲み枠',
		'heading-decoration' => '飾り罫を付けた見出し',
		'photos'             => '並びをずらした組写真',
	);

	foreach ( $patterns as $slug => $title ) {
		$file = get_template_directory() . '/patterns/' . $slug . '.php';
		if ( file_exists( $file ) ) {
			register_block_pattern(
				'mytheme/' . $slug,
				array(
					'title'      => __( $title, 'mytheme' ),
					'categories' => array( 'mytheme' ),
					'content'    => file_get_contents( $file ),
				)
			);
		}
	}
}
add_action( 'init', 'mytheme_block_patterns' );

メリット

  • パターンファイルを保存した瞬間に反映される
  • 複数パターンをまとめて管理できる
  • キャッシュを気にせず開発が進められる

まとめ

  • WordPress の patterns/ ディレクトリは便利だが、キャッシュのせいで反映が遅い
  • 開発中は functions.php + file_get_contents() で登録すれば即反映
  • 本番配布用テーマでは、必要に応じて元の patterns/ ディレクトリ方式に戻すのもアリ

参考URL

WordPress の Block Patterns 全体の仕様(register_block_pattern 等)
Patterns – Block Editor Handbook

テーマで /patterns ディレクトリを使ってパターンを登録する方法
Registering Patterns – Theme Handbook

register_block_pattern() を使って PHP ファイルから内容を読み込む例
StackOverflow の例

「パターンキャッシュ」に関するバグレポート(キャッシュが絶対パスを保持する問題など)
WooCommerce の GitHub Issue #53345

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?