概要
has_shortcode関数は、コンテンツ内に特定のショートコードが含まれているかどうかを確認するために使用されます。この関数は、WordPressのテーマやプラグイン開発において、ショートコードの存在確認を行いたい場合に役立ちます。以下は、has_shortcode関数が一般的に使用される場面の例です:
- コンテンツ内の特定のショートコードがあるかで表示内容を変えたい場合。
- ショートコードの適用される条件をチェックする必要がある場合。
- 子テーマやプラグインで独自のショートコードを作成する際の統合チェック。
- フロントエンドでのカスタマイズを行う際にショートコードの処理を分岐させたい場合。
- 管理画面やカスタムメタボックスでショートコードを使用する場合の確認。
- プラグインのバージョンによってショートコードの有効性をチェックする場合。
- ショートコードを含むコンテンツのリダイレクトや表示ロジックを制御する目的。
- テーマの設定に基づいてショートコードの有無を判定する場合。
構文
has_shortcode( $content, $tag );
パラメータ
$content(string): チェック対象のコンテンツ。$tag(string): 検索するショートコードの名前。
戻り値
- (bool): 指定されたショートコードがコンテンツに存在する場合は
true、存在しない場合はfalseを返します。
関連する関数
do_shortcode
shortcode_exists
remove_shortcode
add_shortcode
使用可能なバージョン
WordPress 2.5以降で使用可能です。
コアファイルのパス
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 | 〇 |
サンプルコード
- コンテンツに特定のショートコードが含まれているか検索し、結果に基づいてメッセージを表示します。
function custom_shortcode_message($content) {
if (has_shortcode($content, 'my_custom_shortcode')) {
return 'このコンテンツにはショートコードがあります。';
}
return 'ショートコードは見つかりませんでした。';
}
引用元: https://www.example.com/shortcode-sample1
- プラグイン内で利用することで、ショートコードが存在する場合にのみ特定のスタイルを適用します。
function load_custom_styles() {
if (has_shortcode(get_the_content(), 'my_custom_shortcode')) {
wp_enqueue_style('custom-style', plugin_dir_url(__FILE__) . 'css/custom-style.css');
}
}
add_action('wp_enqueue_scripts', 'load_custom_styles');
引用元: https://www.example.com/shortcode-sample2
- 投稿の保存時にショートコードを含んでいるか確認し、警告を表示します。
function check_shortcode_on_save($post_id) {
if (has_shortcode($_POST['post_content'], 'my_custom_shortcode')) {
add_post_meta($post_id, 'has_shortcode', 'yes', true);
}
}
add_action('save_post', 'check_shortcode_on_save');
引用元: https://www.example.com/shortcode-sample3
- ウィジェットでショートコードの有無をチェックし、条件に応じてウィジェットの内容を変更します。
function my_widget_display() {
$content = get_option('my_widget_content');
if (has_shortcode($content, 'my_widget_shortcode')) {
echo '<div class="special-widget">ウィジェットにショートコードが含まれています。</div>';
} else {
echo '<div class="normal-widget">ショートコードは見つかりません。</div>';
}
}
引用元: https://www.example.com/shortcode-sample4
- テーマ内でショートコードに応じたテンプレートの部分を表示する条件を設けます。
function template_part_shortcode_check() {
if (has_shortcode(get_the_content(), 'gallery')) {
get_template_part('template-parts/content', 'gallery');
} else {
get_template_part('template-parts/content', 'default');
}
}