ワードプレスのwp_is_block_theme関数の使用方法・解説

概要

wp_is_block_theme関数は、現在のテーマがブロックベースのテーマかどうかを調べるために使用されます。この関数は、主にブロックエディターと互換性のあるテーマを判断する際に役立ちます。具体的には、以下のような機能を実装する場合によく使用されます。

  1. テーマの選択によるコンテンツ表示の切り替え
  2. 特定のスタイルやスクリプトをテーマに基づいて条件付きで読み込む
  3. カスタムウィジェットエリアの登録をテーマに基づいて調整
  4. 編集用のインターフェースの適切な表示
  5. テーマがブロックエディターに対応しているか確認
  6. プラグインでのテーマ制御の実装
  7. ユーザーの体験のカスタマイズ
  8. 他のテーマ機能やフックとの相互作用を調整

構文

wp_is_block_theme();

パラメータ

この関数はパラメータを受け取りません。

戻り値

  • trueまたはfalse: 現在のテーマがブロックテーマであればtrue、そうでなければfalseを返します。

関連する関数

使用可能なバージョン

  • WordPress 5.8.0より利用可能です。

コアファイルのパス

  • /wp-includes/theme.php

この関数のアクションでの使用可能性

アクション 使用例
mu_plugin_loaded
registered_post_type
plugins_loaded
wp_roles_init
setup_theme
after_setup_theme
set_current_user
init
register_sidebar
wp_loaded
send_headers
parse_query
pre_get_posts
wp
template_redirect
get_header
wp_head

wp_is_block_theme関数が特定のワードプレスバージョンで非推奨又は削除された場合はありません。

サンプルコード

1. テーマに応じて異なるスタイルを読み込む

function enqueue_styles() {
    if (wp_is_block_theme()) {
        wp_enqueue_style('block-theme-style', get_template_directory_uri() . '/block-style.css');
    } else {
        wp_enqueue_style('classic-theme-style', get_template_directory_uri() . '/classic-style.css');
    }
}
add_action('wp_enqueue_scripts', 'enqueue_styles');

このコードは、テーマがブロックベースである場合に特定のスタイルシートを読み込み、それ以外の場合は別のスタイルシートを読み込みます。

2. ブロックテーマ用にウィジェットエリアを登録する

function register_custom_widgets() {
    if (wp_is_block_theme()) {
        register_sidebar(array(
            'name'          => __('Custom Widget Area', 'textdomain'),
            'id'            => 'custom-widget-area',
            'before_widget' => '<div class="widget">',
            'after_widget'  => '</div>',
        ));
    }
}
add_action('widgets_init', 'register_custom_widgets');

このコードは、ブロックテーマの場合のみウィジェットエリアを登録します。

3. 特定のテンプレートをサポートする

function theme_template_support() {
    if (wp_is_block_theme()) {
        add_theme_support('block-template');
    }
}
add_action('after_setup_theme', 'theme_template_support');

このコードは、テーマがブロックベースのテーマであれば、ブロックテンプレートのサポートを追加します。

4. フロントエンドでの表示

function display_block_theme_message() {
    if (wp_is_block_theme()) {
        echo '<p>This theme supports block editor features!</p>';
    }
}
add_action('wp_footer', 'display_block_theme_message');

このコードは、ブロックテーマである場合にフッターにメッセージを表示します。

5. 管理画面向けの通知

function admin_block_theme_notice() {
    if (wp_is_block_theme()) {
        echo '<div class="notice notice-info"><p>This is a block theme!</p></div>';
    }
}
add_action('admin_notices', 'admin_block_theme_notice');

このコードは、管理画面においてブロックテーマであることを通知するメッセージを表示します。

この関数について質問する


上の計算式の答えを入力してください