ワードプレスで独自プラグインや設定を作る場合、よく利用するラジオボタン。
チェックされた設定を保存した後、
その設定を読み込んで「checked」を入れる方法の覚書メモ。
ラジオボタンの基本形
ラジオボタンの基本のHTML。
<input type="radio" name="test_item" value="はい" checked="checked">はい
<input type="radio" name="test_item" value="いいえ">いいえはい いいえ
1行目に checked を入れている例。
「checked="checked"」では単に「checked」でもOK。
項目名(「はい」「いいえ」)もクリックできるようにするには labelタグを使う。
書き方は2通り。
1)全体を labelタグで囲む
<label><input type="radio" name="test_item" value="はい" checked="checked">はい</label>
<label><input type="radio" name="test_item" value="いいえ">いいえ</label>
2)label for を使う
<input type="radio" name="test-item" id="item1" value="はい" checked >
<label for="item1">はい</label>
<input type="radio" id="item2"name="test-item" value="いいえ" >
<label for="item2">いいえ</label>
「label for」を使う場合、input要素内の id と 「label for」で指定する値を同じにすることで項目名とラジオボタンの関連付けが行われる。
値を取得して checked を付ける
ラジオボタンの選択状態を取得して、その値に基づいて checked を付ける。
やり方は以下の3通りぐらい。
その1)if で比較する
<?php
function test1(){
$item = get_option( 'item_value' );
?>
<label><input type="radio" name="test_item" value="はい"
<?php if( $item == 'はい' ){ echo ' checked'; } ?> >はい</label>
<label><input type="radio" name="test_item" value="いいえ"
<?php if( $item == 'いいえ' ){ echo ' checked'; } ?> >いいえ</label>
<?php
}
?>(6行目、9行目)
値($item)に対して「はい」か「いいえ」かを if 文でチェックし、
同じであれば echo で「 checked」を表示する、としている。
その2)三項演算子を使う
<?php
function test2(){
$item = get_option( 'item_value' );
?>
<label><input type="radio" name="test_item" value="はい"
<?php echo $item == 'はい' ? ' checked' : ''; ?> >はい</label>
<label><input type="radio" name="test_item" value="いいえ"
<?php echo $item == 'いいえ' ? ' checked' : ''; ?> >いいえ</label>
<?php
}
?>(6行目、9行目)
値($item)に対して「はい」か「いいえ」かを 三項演算子を使って判別している。
三項演算子は以下の形。
- 条件式 ? ①真の場合 : ②偽の場合
条件式が真の場合①が実行され、そうでなければ②が実行される。
echo $item == 'はい' ? ' checked' : '';この場合(6行目、9行目)では、$itemが"はい"に同じであれば、' checked' が表示され、
そうでなければ 「"」(空文字)を表示(つまり何も表示されない)。
言語リファレンス:三項演算子(PHPマニュアル)
その3)checked関数を使う
<?php
function test3(){
$item = get_option( 'item_value' );
?>
<label><input type="radio" name="test_item" value="はい"
<?php checked( $item, 'はい' ); ?> >はい</label>
<label><input type="radio" name="test_item" value="いいえ"
<?php checked( $item, 'いいえ' ); ?> >いいえ</label>
<?php
}
?>ワードプレスには checked を表示するためのchecked関数が用意されている。
使い方は簡単で、
checked($value1, $valu2)という形で $value1、$value2 を比較して、
同じであれば、半角スペース+「checked="checked"」を表示する。
同じでなければ何もしない。
6行目、9行目では $item と「はい」「いいえ」と比較して
同じであれば「 checked="checked"」をサクっといれる、としている。
ワードプレスで独自で設定を作る場合には、
この checked関数を使うのが簡単だしコードも分かりやすいのでおすすめ。


コメント