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

概要

do_shortcode 関数は、WordPress におけるショートコードを変換するための非常に重要な関数です。ショートコードを使用すると、特定の機能やコンテンツを簡潔に挿入することができ、使い勝手が向上します。一般的に、以下のような機能を実装する際によく使われます。

  1. ギャラリーの表示
  2. カスタムコンテンツの挿入
  3. フォームの埋め込み
  4. ウィジェットの表示
  5. カスタム投稿タイプのレンダリング
  6. インラインミュージックプレイヤーの表示
  7. 経時的なコンテンツ変更
  8. データの動的表示

構文

do_shortcode( $content );

パラメータ

  • $content (string): ショートコードが含まれるコンテンツ。

戻り値

  • (string): ショートコードが処理された後のコンテンツ。

関連する関数

使用可能なバージョン

  • WordPress 2.5.0 以降で使用可能。

コアファイルのパス

  • wp-includes/shortcodes.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

サンプルコード

サンプル 1: ショートコードを使って簡単なテキストを表示する

function simple_shortcode() {
    return 'こんにちは、World!';
}
add_shortcode('greeting', 'simple_shortcode');

echo do_shortcode('[greeting]');

このコードは、[greeting] というショートコードを定義し、呼び出すことで「こんにちは、World!」というテキストを表示します。

サンプル 2: ギャラリーのショートコードを使用する

echo do_shortcode('');

このコードは、IDが 1, 2, 3 の画像を含むギャラリーを表示します。

サンプル 3: 画像を表示するショートコードの作成

function image_shortcode($atts) {
    $atts = shortcode_atts(
        array(
            'src' => 'default.jpg',
            'alt' => 'default image',
        ), $atts
    );
    return '<img src="' . esc_url($atts['src']) . '" alt="' . esc_attr($atts['alt']) . '">';
}
add_shortcode('image', 'image_shortcode');

echo do_shortcode('[image src="image.jpg" alt="Sample Image"]');

このコードは、[image] ショートコードを使用して、指定された画像を表示するものです。

サンプル 4: カスタム投稿のリストを表示するショートコード

function list_custom_posts() {
    $args = array('post_type' => 'custom_type', 'posts_per_page' => 5);
    $query = new WP_Query($args);
    $output = '<ul>';
    while ($query->have_posts()) : $query->the_post();
        $output .= '<li>' . get_the_title() . '</li>';
    endwhile;
    $output .= '</ul>';
    wp_reset_postdata();
    return $output;
}
add_shortcode('custom_posts', 'list_custom_posts');

echo do_shortcode('[custom_posts]');

このコードは、カスタム投稿タイプのタイトルをリスト表示するショートコードを作成します。

サンプル 5: フォームのショートコードを処理する

function contact_form_shortcode() {
    return '<form action="submit.php" method="post"><input type="text" name="name" placeholder="名前"><input type="submit" value="送信"></form>';
}
add_shortcode('contact_form', 'contact_form_shortcode');

echo do_shortcode('[contact_form]');

このコードは、シンプルな連絡フォームを表示するショートコードを作成します。

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


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