Trusted WordPress tutorials, when you need them most.
Beginner’s Guide to WordPress
WPBカップ
25 Million+
Websites using our plugins
16+
Years of WordPress experience
3000+
WordPress tutorials
by experts

WordPressでフォームのナビゲーション確認ポップアップを表示する方法

コメントを送信せずにページを閉じてしまったり、フォームが中途半端に入力されたままページを閉じてしまったりするのは迷惑なことです。最近、あるユーザーから、読者にナビゲーションの確認ポップアップを表示できないかという問い合わせがありました。

この小さなポップアップは、ユーザーに警告を発し、ユーザーが誤って中途半端な入力や未送信のフォームを残してしまうのを防ぎます。ユーザーエクスペリエンスを向上させ、訪問者がゼロから何かを始めなければならないのを防ぐ良い方法です。

この投稿では、WordPressのフォームにナビゲーション確認ポップアップを表示する方法を紹介します。

Confirm navigation popup when user leaves a form unsubmitted

ナビゲーション確認ポップアップとは?

ユーザーがあなたのブログにコメントを書いているとしよう。すでに何行もコメントを書いていたのに、気が散ってコメント送信を忘れてしまったとする。さて、もし彼らがブラウザーを閉じてしまったら、コメントする内容は失われてしまいます。

ナビゲーションを確認するポップアップは、コメントするチャンスを与える。

この機能はWordPressの投稿エディター画面で実際に見ることができます。もし未保存の変更があり、ページを去ろうとしたりブラウザーを閉じようとすると、警告ポップアップが表示されます。

Unsaved changes warning popup in WordPress post editor

WordPressのコメントやサイトのフォームにこの警告機能を追加する方法を見てみましょう:

WordPressで未送信のフォームにナビゲーションの確認ポップアップを表示する

このチュートリアルでは、カスタマイザー・プラグインを作成しますが、このチュートリアルの最後にあるプラグインをダウンロードしてサイトにインストールすることもできますので、ご安心ください。

しかし、コードをよりよく理解するために、あなた自身のプラグインを作成してみてください。まずはローカル・インストールまたはステージング・サイトでこれを行うことができます。

始めよう。

まず、コンピューターに新しいフォルダーを作成し、confirm-leavingと名付ける必要があります。confirm-leavingフォルダーの中に別のフォルダーを作成し、jsと名付ける。

メモ帳のようなプレーンテキストエディターを開き、新規ファイルを作成する。その中に以下のコードを貼り付ける:

[php]
<?php
/**
 * Confirm Leaving
 * Plugin Name: Confirm Leaving
 * Plugin URI:  https://www.wpbeginner.com
 * Description: This plugin shows a warning to users when try they forget to hit submit button on a comment form.
 * Version:     1.0.0
 * Author:      WPBeginner
 * Author URI:  https://www.wpbeginner.com
 * License:     GPL-2.0+
 * License URI: http://www.gnu.org/licenses/gpl-2.0.txt
 */

function wpb_confirm_leaving_js() { 

     wp_enqueue_script( 'Confirm Leaving', plugins_url( 'js/confirm-leaving.js', __FILE__ ), array('jquery'), '1.0.0', true );
}
add_action('wp_enqueue_scripts', 'wpb_confirm_leaving_js');
[/php]

このPHP関数は、あなたのサイトのフロントエンドにJavaScriptファイルを追加するだけです。

confirm-leaving.phpをconfirm-leavingフォルダー内に保存してください。

ここで、このプラグインが読み込むJavaScriptファイルを作成する必要がある。

新規ファイルを作成し、その中にこのコードを貼り付ける:

[javascript]
jQuery(document).ready(function($) { 

$(document).ready(function() {
    needToConfirm = false;
    window.onbeforeunload = askConfirm;
});

function askConfirm() {
    if (needToConfirm) {
        // Put your custom message here
        return "Your unsaved data will be lost.";
    }
}

$("#commentform").change(function() {
    needToConfirm = true;
});

 })
[/javascript]

このJavaScriptコードは、ユーザーがコメントフォームに未保存の変更があるかどうかを検出します。ユーザーがページから移動しようとしたり、ウィンドウを閉じようとすると、警告ポップアップを表示します。

このファイルをjsフォルダー内にconfirm-leaving.jsとして保存する必要がある。

両方のファイルを保存すると、フォルダー構造はこのようになります:

Plugin file structure

次に、FTPクライアントを使用してWordPressサイトに接続する必要があります。FTPを使用してWordPressファイルをアップロードする方法については、こちらのガイドをご覧ください。

接続したら、confirm-leavingフォルダーをサイト上の/wp-contents/plugins/フォルダーにアップロードする必要があります。

Uploading plugin files to your WordPress site

その後、WordPressの管理エリアにログインし、プラグインのページにアクセスする必要があります。

インストールしたプラグインの一覧から「Confirm Leaving」プラグインを探し、その下にある「有効化」リンクをクリックします。

Activate plugin

これですべてだ。これで、あなたのサイトの投稿日にアクセスし、コメントフォームの任意のフィールドにテキストを書き込み、送信せずにページを閉じてみることができます。

ポップアップが表示され、未保存の変更があるページを離れようとしていることを警告します。

popup notification warning user about unsaved changes

WordPressの他のフォームに警告を追加する

同じコードベースを使って、WordPressサイトのあらゆるフォームをターゲットにすることができます。ここでは、お問い合わせフォームをターゲットにした例を紹介します。

この例ではWPFormsプラグインを使ってお問い合わせフォームを作成します。あなたのサイトで別のお問い合わせフォームプラグインを使用している場合でも手順は同じです。

お問い合わせフォームを追加したページに移動します。お問い合わせフォームの最初のフィールドにマウスオーバーして右クリックし、ブラウザーメニューから「検査」を選択します。

Finding form ID

<form>タグで始まる行を探してください。formタグの中にID属性があります。

この例では、フォームのIDはwpforms-form-170です。ID属性をコピーする必要があります。

次に、confirm-leaving.jsファイルを編集し、#commentformの後にID属性を追加する。

フォームのIDは、#commentformで本当に〜してもよいですか?また、フォームのID属性のプレフィックスとして#記号を追加する必要があります。

コードはこのようになる:

[javascript]
jQuery(document).ready(function($) { 

$(document).ready(function() {
    needToConfirm = false;
    window.onbeforeunload = askConfirm;
});

function askConfirm() {
    if (needToConfirm) {
        // Put your custom message here
        return "Your unsaved data will be lost.";
    }
}

$("#commentform,#wpforms-form-170").change(function() {
    needToConfirm = true;
});

 })
[/javascript]

変更を保存し、ファイルをサイトにアップロードしてください。

これで、お問い合わせフォームの任意のフィールドに任意のテキストを入力し、フォームを送信せずにページを閉じようとすることができます。ポップアップが表示され、未保存の変更があることを警告します。

confirm-leavingプラグインはこちらからダウンロードできます。コメントフォームのみを対象にしていますが、プラグインを編集して他のフォームを対象にすることも可能です。

以上です。この投稿がWordPressフォームのナビゲーションポップアップの確認に役立てば幸いです。また、ビジネスサイトに必須のWordPressプラグインとツールをチェックしたり、ブログのトラフィックを増やす方法についての究極のガイドを読むこともできます。

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.

情報開示 私たちのコンテンツは読者支援型です。これは、あなたが私たちのリンクの一部をクリックした場合、私たちはコミッションを得ることができることを意味します。 WPBeginnerの資金源 をご覧ください。3$編集プロセスをご覧ください。

アバター

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi with over 16 years of experience in WordPress, Web Hosting, eCommerce, SEO, and Marketing. Started in 2009, WPBeginner is now the largest free WordPress resource site in the industry and is often referred to as the Wikipedia for WordPress.

究極のWordPressツールキット

ツールキットへの無料アクセス - すべてのプロフェッショナルが持つべきWordPress関連製品とリソースのコレクション!

Reader Interactions

20件のコメント返信を残す

  1. Syed Balkhi says

    Hey WPBeginner readers,
    Did you know you can win exciting prizes by commenting on WPBeginner?
    Every month, our top blog commenters will win HUGE rewards, including premium WordPress plugin licenses and cash prizes.
    You can get more details about the contest from here.
    Start sharing your thoughts below to stand a chance to win!

  2. Igor says

    Tried to use your code in bbpress forum. Unfortunately no popup message appears after user dose not post his comment. Tried all variations of changing id in JS file but still nothing appears.

  3. Bob Garrett says

    Further to my previous query I have now tried using the form’s parent div id and modified the code. This almost works but…

    The text shown by the pop-up is not the text entered in the code.

    Even if the form is completed and submit hit, then going to another page still results in the warning.

    How can I resolve this?

  4. Tom Kelley says

    Have tried this vvvvv to no avail. Working with Gravity Forms. All else works well, but the warning still comes up when hitting the submit button on a completed form. Any advice?

    WPBeginner Support
    Nov 27, 2016 at 6:52 am

    Hi Bonnie,

    We tested the plugin with WPForms and it worked. You will need to edit the confirm-leaving.js file and replace #commentform with the wpforms container div id. Typically it is wpforms-12 where 12 is the ID of your form. You can also see it using the inspect element tool in your browser.

    • Bonnie Ramthun says

      I’m still trying to figure out how to make sure the popup DOESN’T appear when the user presses the “Submit” button. The confirm leaving popup shouldn’t appear if the user has entered all the information required, but this code makes it pop up every time.

      I would so appreciate the help, if there is a solution available.

  5. Swayam Dhawan says

    I Need the same function when someone navigate from particular page in website and while click on stay , they must navigate to home page of the website.

    waiting for the response.

  6. Bonnie Ramthun says

    I am so happy for your wonderful confirm navigation code! I need it desperately because many of my clients users can’t get it through their head that they need to press the “Submit” button on the form.

    The code works perfectly, except for one problem. When I press the “Submit” button on my WPForms form, the confirm navigation code pops up. I would like the “confirm navigation” to happen only when the user doesn’t press the “Submit” button. I can’t figure out how to do this. Can you help?

    • WPBeginner Support says

      Hi Bonnie,

      We tested the plugin with WPForms and it worked. You will need to edit the confirm-leaving.js file and replace #commentform with the wpforms container div id. Typically it is wpforms-12 where 12 is the ID of your form. You can also see it using the inspect element tool in your browser.

      管理者

  7. Will C says

    I have two separate multi-page gravity forms on my site. When this plugin is active, I get a confirmation popup when clicking “Next Step” on one of the forms (undesired), but not the other. Are you aware of any issues with gravity forms and “window.onbeforeunload”? Thanks

      • Nipa Sarker says

        I ma using the code for buddy-press multi step create group from.It is working fine except while clicking on the next step button or save button it is showing the same alert.
        I ma using the form id “#create-group-form” instead of the #commentform

  8. Luis Zarza says

    Hi, nice post!

    It helped a lot. But your solution won’t work while logged in. It only works for users that fill in the form and are logged out. I need it also to work for logged in users, please!
    Could you provide a solution for that?

    Thanks.

    • Luis Zarza says

      Sorry, it does actually works when you create the plugin. At first I did it only throwing the JS to the page I wanted without creating the plugin, because I didn’t want the script to be loaded on all the pages of my site.

    • WPBeginner Support says

      Contact Form 7 uses an ID with all the forms. The line that contains form ID will look something like this:

      <div role="form" class="wpcf7" id="wpcf7-f85-p11-o1" lang="en-US" dir="ltr">
      

      In this example, the form’s ID attribute is wpcf7-f85-p11-o1. Hope this helps.

      管理者

  9. Betty L Van Fossen says

    I have two problems. One I get these pop up in my mail all the time,q it’s aggravating. I’m 89 in yrs.therefore a little short on patience and I start using my pointer to fast hitting other things, so I get myself in lots of problems. Two –guess(I know) I have to many cookies they say. What are the cookies –how do I eleminate them? What do you mean subscribe without commenting. I prefer the e-mail. O.K..to personal and meaningful conversation.

        • Betty L Van Fossen says

          Safari said I could not get in cause I had to many cookies. In the meantime I was on my e-mail and the pop ups came on, while on my e-mail they are always popping up. I got on google and asked for help on cookies and pop ups and gave me lots to choose from. Now word press got in here, what is word press. I’m not going to write a book,just NEED HELP. Answer by e-mail. I’m turning you off now I’m really tired now.

返信を残す

コメントありがとうございます。すべてのコメントは私たちのコメントポリシーに従ってモデレートされ、あなたのメールアドレスが公開されることはありませんのでご留意ください。名前欄にキーワードを使用しないでください。個人的で有意義な会話をしましょう。