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

概要

add_shortcode 関数は、ショートコード(独自タグ)を追加するための関数です。この関数を使用することで、WordPressの投稿やページ内に独自の機能を短いコードで埋め込むことができます。主に以下のような機能を実装する際によく利用されます:

  1. ギャラリーの表示機能
  2. カスタムフォームの作成機能
  3. 動画やオーディオの埋め込み機能
  4. サードパーティAPIのデータ表示
  5. 記事の特定部分の強調表示
  6. タイマーやカウントダウンの表示機能
  7. SNSのシェアボタンの追加
  8. 特定のカテゴリの投稿をリスト表示する機能

構文

add_shortcode( $tag, $func );

パラメータ

  • $tag (string): ショートコードの名前。
  • $func (callable): ショートコードが呼び出されたときに実行される関数。

戻り値

add_shortcode 関数は成功した場合に true を返します。

関連する関数

使用可能なバージョン

add_shortcode 関数は、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: 基本的なショートコード

add_shortcode('hello', 'hello_shortcode');

function hello_shortcode() {
    return 'こんにちは、世界!';
}

このサンプルコードは [hello] というショートコードを追加し、ページ内に「こんにちは、世界!」と表示します。

サンプル2: 属性付きショートコード

add_shortcode('greet', 'greet_shortcode');

function greet_shortcode($atts) {
    $atts = shortcode_atts(
        array('name' => 'ユーザー'),
        $atts
    );
    return 'こんにちは、' . esc_html($atts['name']) . '!';
}

このサンプルコードは [greet name="太郎"] と呼び出すと、「こんにちは、太郎!」と表示します。デフォルトで「ユーザー」という名前が使用されます。

サンプル3: HTMLを含むショートコード

add_shortcode('button', 'button_shortcode');

function button_shortcode($atts) {
    $atts = shortcode_atts(
        array('url' => '#', 'text' => 'クリック'),
        $atts
    );
    return '<a href="' . esc_url($atts['url']) . '" class="button">' . esc_html($atts['text']) . '</a>';
}

このサンプルコードは button ショートコードを実装し、指定したURLにリンクするボタンを生成します。

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

add_shortcode('recent_posts', 'recent_posts_shortcode');

function recent_posts_shortcode($atts) {
    $atts = shortcode_atts(array('num' => 5), $atts);
    $query = new WP_Query(array('posts_per_page' => $atts['num']));
    $output = '<ul>';
    while ($query->have_posts()) {
        $query->the_post();
        $output .= '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
    }
    $output .= '</ul>';
    wp_reset_postdata();
    return $output;
}

このサンプルコードは [recent_posts num="3"] のショートコードを使用することで、最近の投稿をリスト表示します。

サンプル5: インラインスタイル付きのショートコード

add_shortcode('highlight', 'highlight_shortcode');

function highlight_shortcode($atts, $content = null) {
    return '<span style="background-color: yellow;">' . do_shortcode($content) . '</span>';
}

このサンプルコードは [highlight]テキスト[/highlight] を使用することで、テキストをハイライト表示します。このスタイルはインラインで設定されています。

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


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