Sleeping Murder

Music, chords, art, design, things.

WordPressの再利用ブロック(パターン)をショートコードで呼び出します

This article contains advertisements.

いつも探して困るコードなので書いときます。

WordPressの再利用ブロック(パターン)をショートコードで呼び出します。

/**
 * 再利用ブロックをショートコードで呼び出す
 * 例: [my_block id="再利用ブロックのID"]
 */
function display_reusable_block($atts) {
    // 引数の設定(idがない場合は何もしない)
    $atts = shortcode_atts(array(
        'id' => ''
    ), $atts);

    if (empty($atts['id'])) {
        return '';
    }

    // 指定したIDのブロックを取得
    $reusable_block = get_post($atts['id']);

    if ($reusable_block && $reusable_block->post_type === 'wp_block') {
        // ブロックの内容を解析してHTMLとして出力
        return apply_filters('the_content', $reusable_block->post_content);
    }

    return '';
}
add_shortcode('my_block', 'display_reusable_block');

よく使うのによく失念します。

hirochan

Hi there! I’m hirochan

The creator of this site. Building websites is my passion, and I love listening to rock and metal music. In my daily life, I’m just an ordinary homemaker. I absolutely adore coming up with designs, so you might notice this blog’s look changing depending on my mood!