ショートコード : WordPress

Pocket

ショートコードの覚書。

id属性とclass属性を持つ見出しタグh3をショートコードで記述する。

<?php
function h3_func($atts, $content = null) {
	extract(shortcode_atts(array(
		'id' => '',
		'class' => '',
	), $atts));
	$html = '<h3';
	if ($id) {
		$html .= ' id="' . $id . '"';
	}
	if ($class) {
		$html .= ' class="' . $class . '"';
	}
	$html .= '>' . $content . '</h3>';
	return $html;
}
add_shortcode('h3', 'h3_func');
?>

ビジュアルエディタに下記のように入力する。

[h3 id="foo" class="bar"]サンプル[/h3]

下記のHTMLコードが返る。

<h3 id="foo" class="bar">サンプル</h3>

ショートコードのコールバック関数h3_funcへはWordPressによって2つの引数$attsと$contentが渡る。
$attsはショートコードの属性の配列が渡される(例では$atts = array(‘id’ =>’foo’, class=”bar”))。
$contentはショートコードに囲まれた文字列が渡される(例ではサンプル)。

$attsはshortcode_atts関数の第2引数になる。shortcode_atts関数は第1引数の配列と第2引数の配列をマージする。第2引数の要素の中に第1引数の配列でデフォルト値を指定していない要素があればその要素は破棄する。

[h3 id="foo" class="bar" name="hoge"]サンプル[/h3]

例えばname属性は、上記のようにショートコードを記述した場合はshor_code関数がマージする際に第1引数にname要素のデフォルト値が設定されてないので破棄される。

» ショートコード API – WordPress Codex 日本語版
» Function Reference/shortcode atts « WordPress Codex

WordPress Codexで推奨されているショートコードのコールバック関数の記述。

function my_shortcode_handler( $atts, $content = null ) {
   extract( shortcode_atts( array(
      'attr_1' => 'attribute 1 default',
      'attr_2' => 'attribute 2 default',
      // ...etc
      ), $atts ) );
}

» ショートコード API – WordPress Codex 日本語版

ショートコードサンプル

» WordPress複数改行対応ショートコード : WordPress

コメント

No comments yet.

コメントの投稿

改行と段落タグは自動で挿入されます。
メールアドレスは表示されません。