概要
do_shortcode
関数は、WordPress におけるショートコードを変換するための非常に重要な関数です。ショートコードを使用すると、特定の機能やコンテンツを簡潔に挿入することができ、使い勝手が向上します。一般的に、以下のような機能を実装する際によく使われます。
- ギャラリーの表示
- カスタムコンテンツの挿入
- フォームの埋め込み
- ウィジェットの表示
- カスタム投稿タイプのレンダリング
- インラインミュージックプレイヤーの表示
- 経時的なコンテンツ変更
- データの動的表示
構文
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]');
このコードは、シンプルな連絡フォームを表示するショートコードを作成します。