こんにちは、平田智剛です。
今回は、wordpress上で簡単に穴埋め問題が作れるショートコードを自作してみました。
穴埋め問題のサンプル
[fill_blank A=弱者男性 B=8 C=4]
この法人は、「特定非営利活動法人日本{{A}}センター」といいます。
設立日(2022年{{B}}月{{C}}日)時点において、
日本で唯一、「{{A}}」の文字列を名称に含む法人となっています。
[/fill_blank]
上記のショートコードを記事に挿入すると、次のようになります。
この法人は、「特定非営利活動法人日本センター」といいます。
設立日(2022年月日)時点において、
日本で唯一、「」の文字列を名称に含む法人となっています。
導入方法
functions.php
の末尾に、次の内容を追記します。
( functions.php
をご存じでない方は、こちらのサイトを参考にしてください )
function fill_blank_func( $atts, $content = "" ){
$keys = array_keys($atts);
foreach($keys as $key){
$value = $atts[$key];
$button = "<span class='fill_blank_$key'><button onclick='";
$button.= <<<EOT
(function(){
var elements = document.getElementsByClassName("fill_blank_$key");
for( let i = 0 ; i < elements.length ; i ++ ) {
var element = elements[i];
var button = element.children[0];
var answer_span = element.children[1];
if (answer_span.style.display == "inline"){
answer_span.style.display = "none";
button.style= "";
button.innerHTML = " " + button.innerHTML + " ";
}else{
answer_span.style.display = "inline";
button.style = "font-size: 0.2rem";
button.innerHTML = button.innerHTML.replaceAll(" ", "");
}
}
})()
EOT;
$button.= "'> " . strtoupper($key). " </button><span style='display:none; color:red'>$value</span></span>";
$content = str_ireplace( "{{".$key."}}" , $button , $content);
}
return $content;
}
add_shortcode('fill_blank', 'fill_blank_func');
やっていることとしては、穴の名前(サンプルでいう「A」~「C」)ごとにclass
属性を与え、
各class
に対してjavascriptを使い、穴の中身(答え)に対応する要素のstyle
属性、display
プロパティを切り替えることにより、表示/非表示を入れ替えるというものです。
同じ記事が、qiitaでも公開されています!

Wordpress用のショートコードを自作して穴埋め問題を簡単に作れるようにしてみた - Qiita
1. 用途wordpressの記事に「穴埋め問題」を埋め込みたい時などに参考にしてください。2. サンプルこの法人は、「特定非営利活動法…
コメント
Heya i am for the first time here. I came across this board and
I to find It really useful & it helped me out much. I hope to present one thing again and aid others
such as you helped me.
I relish, lead to I discovered exactly what I used to be
looking for. You have ended my four day lengthy hunt!
God Bless you man. Have a great day. Bye
Hey there! I just want to offer you a huge thumbs up for your great info you have got here on this post.
I am coming back to your blog for more soon.