Contact Form 7で自動返信メールの件名を分岐させる方法。

Contact Form 7で自動返信メールの件名を分岐させる方法。

こんにちは! エンジニアの奥井です。
最近、WordPressのフォーム作成プラグインContact Form7(以下、CF7)で実装作業を行い、困ったことが発生したので、
解決した際の手順を皆様にも共有しようと思い筆を取った次第です。

やりたかったこと 

今回やったのは「ラジオボタンでお客様にお問い合わせ種別を選択してもらい、それに応じて自動返信メールの件名を変更する」という実装です。
自動返信メールの件名自体はCF7の管理画面から設定できるのですが、分岐をするためにはphpファイルを編集する必要がありました。

やったこと

ここからは実際のコード(からお客様の社名や実際の選択肢を変えたもの)を見ながら解説します。

<div class="list clearfix">
  <dl>
    <dt><span class="required">必須</span>お問い合わせ種別</dt>
    <dd>
      <div>
        [radio contact-type use_label_element "新規ご依頼に関するお問い合わせ" "サイト改修に関するお問い合わせ" "協業に関するお問い合わせ" "その他のお問い合わせ"]
      </div>
    </dd>
  </dl>

上は4択のラジオボタンがあるパターンです。これらの選択それぞれで件名を変えるようにします。
明快に答えを書くと、functions.phpに以下のコードを追加します。

add_filter('wpcf7_mail_components', function ($components, $contact_form, $mail) {

  $submission = WPCF7_Submission::get_instance();
  if (!$submission) return $components;
  $data = $submission->get_posted_data();

  $which = method_exists($mail, 'name') ? $mail->name() : 'mail';

  $contact_type = $data['contact-type'][0] ?? '';

  if ($which === 'mail') {
    if ($contact_type === '新規ご依頼に関するお問い合わせ') {
      $components['subject'] = '【新規】' . $components['subject'];
    } elseif ($contact_type === 'サイト改修に関するお問い合わせ') {
      $components['subject'] = '【改修】' . $components['subject'];
    } elseif ($contact_type === '協業に関するお問い合わせ') {
      $components['subject'] = '【協業】' . $components['subject'];
    } else {
      $components['subject'] = '【その他】' . $components['subject'];
    }
  }

  if ($which === 'mail_2') {
    $components['subject'] = '【株式会社ネクストページ】お問い合わせありがとうございます';
  }

  return $components;
}, 10, 3);

各コードの解説をします。

add_filter('wpcf7_mail_components', function ($components, $contact_form, $mail) {

  $submission = WPCF7_Submission::get_instance();
  if (!$submission) return $components;
  $data = $submission->get_posted_data();

まずこの部分で投稿データの取得を行います。

  $which = method_exists($mail, 'name') ? $mail->name() : 'mail';

続いてこの部分では、「メール」と「メール2」のどちらの設定を処理しているか指定します。
「メール」は内部への自動返信、「メール2」は入力された方への自動返信の設定です。

  $contact_type = $data['contact-type'][0] ?? '';

ここでラジオボタンの値を取得します。フォームのname属性に対応します。

  if ($which === 'mail') {
    if ($contact_type === '新規ご依頼に関するお問い合わせ') {
      $components['subject'] = '【新規】' . $components['subject'];
    } elseif ($contact_type === 'サイト改修に関するお問い合わせ') {
      $components['subject'] = '【改修】' . $components['subject'];
    } elseif ($contact_type === '協業に関するお問い合わせ') {
      $components['subject'] = '【協業】' . $components['subject'];
    } else {
      $components['subject'] = '【その他】' . $components['subject'];
    }
  }

ラジオボタンの値($contact_typeの値)で分岐させます。

  if ($which === 'mail_2') {
    $components['subject'] = '【株式会社ネクストページ】お問い合わせありがとうございます';
  }

最後のこの部分は「メール2」の件名を変更するなら使います。

さいごに

上記のコードを使っていただければ自動返信メールの件名を変えることができます。
自分で調べても解決法が出てこなかったので、上長の力を借りてなんとかコードを作ることができました。
Contact Form 7はよく使われるはずなのにネット上の情報が少ないイメージがありますので、
今後も記事を出せるようにしたいですね。