ContactForm7で現在ページのURLを送る方法。 #カスタマイズ

2023.05.27

Logging

おはようございます。ContactForm7で現在ページのURLを送る方法です、全ての記事の下にお問い合わせフォームを設置している人はあまりいないかもしれないけれど。そのあまりいない人の一人です😂。

記事の下にショートコードを設置するにはプラグインを自作するか、テンプレート内に埋め込むかどちらかだと思います。自分は前者のプラグインを自作してショートコードを埋め込んでいます。

ショートコードを埋め込むコードはこんなコードです。

<?php
do_shortcode('[contact-form-7 id="XXXX" title="comment"]')

これで全記事にショートコードを埋め込むことが可能ですがこれだけでは動きません。こんな感じのプラグインを作ってみてください。プラグインの設置方法などはググって下さい。

<?php
/*
  Plugin Name: comment-add
  Plugin URI:
  Description: 記事の下にアドセンス広告などを貼り付けるのに使用
  Version: 1.0.0
  Author: @zip358com
  Author URI: https://www.zip358.com
 */


function comment_add($content)
{
    if (is_single() && 'post' == get_post_type()) {
        $content = $content.do_shortcode('[contact-form-7 id="xxxx" title="comment"]');
        return $content;
    } else {
        return $content;
    }
}
add_filter('the_content', 'comment_add');
remove_filter('the_content', 'wpautop');

これだけでは、どのページから問い合わせしたのか分からないので、名前などの入力欄以外に入力欄を設置します。次に設置したそのNoを控えて下さい。

<script>
//Contact Form 7 現在ページのURL
if(document.querySelectorAll("[name='text-564']")){
    [...document.querySelectorAll("[name='text-564']")].forEach(elm=>{
        elm.setAttribute("type","hidden");
        elm.value = decodeURIComponent(location.href);
    });
}
</script>

上記のコードを</body>タグ直前に設置してください。設置後、text-564を控えたNoに変更シテクダサイこれで設置が完了です☹。

⚠ContactForm7のメール送信欄にも控えたNoを設置してください。これで完了です!!
最後に送信のご確認を忘れずに😐。

タグ

add_filter, body, comment-add, decodeURIComponent, description, document.querySelectorAll, elm, else, foreach, hidden&quot, lt, php, php do_shortcode, quot, remove_filter, return, setAttribute, title, Version, wpautop,