LoginSignup
0
0

More than 1 year has passed since last update.

ワードプレスのフォームの生年月日を楽に実装する

Posted at

ワードプレスのフォームの入力欄でoptionの誕生日などの年を全て打たなくてもいいようにphpを組み合わせて楽に実装できたらいいですね。実装方法を調べてみると良い記事を見つけたので紹介します。

add_filter('mwform_choices_mw-wp-form-xxx', 'mwform_add_birthday_options', 10, 2);
function mwform_add_birthday_options($children, $atts) {
  if ($atts['name'] === 'birthday_year') {
    $children[''] = '西暦';
    $current_year = date('Y');
    $start_year = $current_year - 70;
    for ($i = $start_year; $i <= $current_year; $i++) {
      $children[$i] = $i;
    }
  } 
  if ($atts['name'] === 'birthday_month') {
    $children[''] = '月';
    for ($i = 1; $i <= 12; $i++) {
      $children[$i] = $i;
    }
  }
  if ($atts['name'] === 'birthday_day') {
    $children[''] = '日';
    for ($i = 1; $i <= 31; $i++) {
      $children[$i] = $i;
    }
  }
  return $children;
}

基本は下の参考記事のままで、変えたぶぶんだけ載せます。月と日は固定で1〜12月、1〜31日まで出ます。年は今年から70年前まで遡ってoptionタグが生成されます。これだとコードを更新する必要がないので楽です。

さらに私は初期値の色を変えたかったので、もう一工夫しました。

jQuery(function () {
  const Select = jQuery('.rec-select-birthday');
  Select.attr('required', true);
});
.rec-select-birthday {
  width: 100%;
  &:invalid {
    color: #b2b2b2;
  }

rec-select-birthdayはセレクトタグにつけます。jQueryでrequired属性をつけて、上記のCSSを当てることで、最初の文字をうす灰色にできました。
いろいろ試行錯誤して上記のコードになりました。探せばもっとよい方法があるかもです。

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0