wordpressでショートコードで動くプラグインを作る

もう手垢もついてますが、読んでいただいている方からのリクエストよりwordpressに独自のショートコードを制作し、出力する方法をご紹介します。

function.phpにでも書いてくだされば機能します。

概要
ショートコードで囲んだ「, 」カンマ区切りの文字列を、<li></li>でコーディングする動きを作ります。

[list_garo8]1,2,3,4,5,6,7,8[/list_garo8]

と書いた場合にリストとして表示されます。コードは↓

function list_garo($atts,$content=null){

extract(shortcode_atts(
array(
'class'=>'',
'float'=>'none',
),$atts)
);

$content=do_shortcode($content);

if(isset($content)){
	$values = explode(',',$content);
	$count = count($values);
	$float="style="float:${float};"";
	$output_html="
	for($i=0; $i < $count; $i++){
		$output_html .= "</pre>
<ul>
	<li>";
		$output_html .=$values[$i]."</li>
</ul>
<pre>

";

		}
		if($float != 'none'){
		$output_html.="</pre>
<div style="clear: both;"></div>
<pre>
";

		}
		$output_html.="

";
	return $output_html;

	}	

	else{ return '';}

	}
add_shortcode( 'list_garo8','list_garo');


作る関数は
function list_garo($atts,$content=null);


とします。関数名はその他の関数と名前がタブらないようにつけてくださいね。

引数$attsは後ほどショートコード内で設定できる値、「属性」の情報が渡されます。$contentは、ショートコードで囲まれたテキストを表します。

それでは一つ一つ見ていきます。
function list_garo($atts,$content=null){

extract(shortcode_atts(
array(
'class'=>'',
'float'=>'none',
),$atts)
);

$content=do_shortcode($content);
//ここに後でif(isset($content){}を入れます。
 }
add_shortcode( 'list_garo8','list_garo');


extract(shortcode_atts(
array(
‘属性名’=>’値’,
‘属性名’=>’値’,
),$atts)
);

は、属性名をキーとした配列を作り出します。ショートコードの作り方として覚えておいていください。

$content=do_shortcode($content);

は、ショートコードでショートコードを囲ってしまった場合の対処です。
do_shortcode();は囲ったショートコードの機能を正常に動かすための関数です。

if(isset($content)){
	$values = explode(',',$content);
	$count = count($values);
	$float="style="float:${float};"";
	$output_html="
	for($i=0; $i < $count; $i++){
		$output_html .= "</pre>
<ul>
	<li>";
		$output_html .=$values[$i]."</li>
</ul>
<pre>

";

		}


if(isset($content)){ }の中身を見ます。
$contentがある場合(ショートコードで囲ったテキストがある場合)に関数を実行させます。ここでは、explode(‘分割する文字’,配列のもと);を使い、$contentを分解して配列にします。カンマで区切って配列を作ります。それを$valuesに代入します。

$countに配列の個数を代入します。count(配列);は配列の要素の数を返してくれます。

$floatは後々、ショートコードの属性でfloatを指定出来るようにしてあります。

$output_htmlはテキストを表示させるための変数として<ul style=”list-style-type: none; clear:both;”>をあてがいます。

後は、$countent配列の要素の数だけ、製成したいHTMLを、for文を使って組み上げます。$output_htmlにfor文内で製成したHTMLを追記していく形をとります。returnを使って$output_htmlを出力します。
if($float != 'none'){
		$output_html.="</pre>
<div style="clear: both;"></div>
<pre>
";

		}
		$output_html.="
";
	return $output_html;

	}

	else{ return '';}

製成が終わったら、ショートコードを登録します。ショートコードの登録は

add_shortcode( ‘ショートコード名’,’ショートコードを適応させる関数名’);

を使用します。ここでは、
add_shortcode( ‘list_garo8′,’list_garo’);

となります。このような簡単なコードであれば、簡単ですが、複雑になるとクラスを製成して制作した方がラクな場合があります。

次回はこのコードをプラグインにする方法をご紹介します。

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

次のHTML タグと属性が使えます: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

WP-SpamFree by Pole Position Marketing