MW WP Formでautocomplete属性を指定する方法
WordPressのお問い合わせフォームプラグイン「MW WP Form」で、inputタグを入れようとすると
このようなタグが入ります。
[mwform_text name="name" id="name"]
autocomplete="name"を入れたいので、強引にこのように変えても
[mwform_text name="name" id="name" autocomplete="name"]
出力されるタグには反映されません。
<input type="text" name="name" id="name" size="60" value="">
という訳で、MW WP Formでautocomplete属性など、「属性」を設定する方法をご紹介します。
目次
jQueryでやる方法
JavaScriptで指定してしまいます。
サンプルソースです。
$(function(){
//MW WP Form autocomplete属性付与
const formAttr = [
//["name属性値", "autocomplete属性値"] で記述
["name", "name"],
["year", "bday-year"],
["month", "bday-month"],
["day", "bday-day"],
["zip", "postal-code"],
["pref", "address-level1"],
["addr", "address-line1"],
["bill", "address-line2"],
["tel_ext", "tel-extension"],
["tel", "tel"],
["email", "email"],
["confirm", "email"]
];
const formAttrLen = formAttr.length;
for(let i=0; i<formAttrLen; i++){
$("[name="+formAttr[i][0]+"]").attr("autocomplete", formAttr[i][1]);
}
});
「formAttr」配列に、適宜追加してください。
すると、例えばこのようなタグには
<input type="text" name="pref" id="pref" size="60" value="">
このようにautocomplete値が設定されます。
<input type="text" name="pref" id="pref" size="60" value="" autocomplete="address-level1">
フィルターフックでやる方法
プラグインのフィルターフックには使えそうなものが無かったので
WordPressのフィルターフックを使ってthe_content()ごと書き換えます。
以下を「functions.php」に貼り付けてください。
//MW WP Form autocomplete属性付与
function mwwpform_autocomplete($contents){
if(is_page('contact')){ //contactページのとき
$form_attr = array(
//["name属性値", "autocomplete属性値"] で記述
["name", "name"],
["year", "bday-year"],
["month", "bday-month"],
["day", "bday-day"],
["zip", "postal-code"],
["pref", "address-level1"],
["addr", "address-line1"],
["bill", "address-line2"],
["tel_ext", "tel-extension"],
["tel", "tel"],
["email", "email"],
["confirm", "email"]
);
foreach($form_attr as $attr){
$contents = str_replace('name="'.$attr[0].'"', 'name="'.$attr[0].'" autocomplete="'.$attr[1].'"', $contents);
}
return $contents;
}else{
return $contents; //contact以外のページのときはそのまま返す
}
}
add_filter('the_content', 'mwwpform_autocomplete', 12);
$form_attr の配列に適宜追加するのと
if(is_page('contact')) のところの条件も適宜変更してください。
すると、例えばこのようなタグには
<input type="text" name="pref" id="pref" size="60" value="">
このようにautocomplete値が設定されます。
<input type="text" name="pref" autocomplete="address-level1" id="pref" size="60" value="">
お役に立てましたら応援をお待ちしております!
頂いた応援は子育てに活用させていただきます。
または以下のボタンからなにか買って応援 (PR)
Amazon
楽天市場
Yahoo!ショッピング