BLOG

ブログ

  • Web制作

Contact Form 7 遷移元の情報をフォームに渡す

Contact Form 7 遷移元の情報をフォームに渡す

Contact Form 7 のフォームを使用して、遷移元の情報をフォームに渡すやり方を紹介します。

例えば、求職者向けにお仕事紹介サイトを制作したとします。お仕事紹介情報をカスタム投稿(カスタム投稿名:job)で作って、シングルページに「エントリー」ボタンを設置します。

「エントリー」ボタンを押して遷移した先のページのエントリーフォームに、遷移元ページの情報を元に、エントリーする「お仕事名」等を自動で入力された状態で表示します。

《functions.php》

function recform_data_filter($tag)
{
    if (!is_array($tag))
        return $tag;
        if (isset($_POST['entry-ttl'])) {
            $name = $tag['name'];
            if ($name == 'entry-ttl')
                $tag['values'] = (array) $_POST['entry-ttl'];
        }
        if (isset($_POST['entry-number'])) {
            $name = $tag['name'];
            if ($name == 'entry-number')
                $tag['values'] = (array) $_POST['entry-number'];
        }
    return $tag;
}
add_filter('wpcf7_form_tag', 'recform_data_filter');

“entry-ttl” , “entry-number” はContact Form 7 のフォームタグの名前です。

《single-job.php》

<form class="entry-btn" action="<?php echo home_url(); ?>/entry/" method="post">
        <input type="hidden" name="entry-ttl" value="<?php the_title(); ?>">
        <input type="hidden" name="entry-number" value="<?php the_field('job_number',$post->ID); ?>">
        <input type="submit" value="エントリー">
</form>

今回の例ではカスタム投稿のタイトルを Contact Form 7 のフォームタグ名”entry-ttl”に、カスタムフィールド名 “‘job_number” のデータを Contact Form 7 のフォームタグ名”entry-number” に渡しています。