[WordPress General] Shortcode をウィジェットや PHP ファイル内で利用する方法

memo.

[markdown]
サンプルとして、`[hello]` というショートコードで `Hello, world!` というテキストを表示する function を作成します。

> * [ショートコード API – WordPress Codex 日本語版](https://wpdocs.osdn.jp/%E3%82%B7%E3%83%A7%E3%83%BC%E3%83%88%E3%82%B3%E3%83%BC%E3%83%89_API)

“`php:functions.php
function hello_world() {
return ‘Hello, world!’;
}
add_shortcode( ‘hello’, ‘hello_world’ );
“`

## 記事本文で利用する

本文中にショートコードを書きます。

“`prettyprinted
[hello]
“`

## テキストウィジェットの中でショートコードを利用する

`add_filter` で有効化します。

> * [関数リファレンス/do shortcode – WordPress Codex 日本語版](http://wpdocs.osdn.jp/%E9%96%A2%E6%95%B0%E3%83%AA%E3%83%95%E3%82%A1%E3%83%AC%E3%83%B3%E3%82%B9/do_shortcode)

“`php:functions.php
add_filter( ‘widget_text’, ‘do_shortcode’ );
“`

ウィジェットのテキストエリアにショートコードを書きます。

“`prettyprinted
[hello]
“`

## PHP ファイル内で利用する

テンプレートや functions.php 内などで利用したい場合、`do_shortcode` を利用します。

“`php

“`

事前に定義確認をすると良さそうです。

> * [PHP: class_exists – Manual](http://php.net/manual/ja/function.class-exists.php)
> * [PHP: function_exists – Manual](http://php.net/manual/ja/function.function-exists.php)

“`php
if ( function_exists( ‘hello_world’ ) ) {
echo do_shortcode( ‘[hello]’ );
}
“`
[/markdown]