wp_referer_field()


WordPress関数wp_referer_field()は、リファラフィールド(hidden input要素)を生成し、フォーム送信時の元のURL情報を保持します。

構文

wp_referer_field();

例1: フォームにリファラフィールドを追加

フォームにリファラフィールドを追加して、送信元の情報を含める基本的な例です。

<form method="post" action="">
    <?php wp_referer_field(); ?>
    <input type="text" name="example" />
    <button type="submit">送信</button>
</form>

例2: 非公開投稿の管理に使用

非公開投稿の操作中に元のURLに戻るリンクを生成します。

<form method="post" action="">
    <?php wp_referer_field(); ?>
    <button type="submit">保存</button>
</form>

例3: セキュリティトークンと併用

リファラフィールドをセキュリティトークン(nonce)と組み合わせて使用し、送信データの検証を行います。

<form method="post" action="">
    <?php wp_nonce_field('example_action', 'example_nonce'); ?>
    <?php wp_referer_field(); ?>
    <input type="text" name="data" />
    <button type="submit">送信</button>
</form>

例4: カスタム管理ページで使用

カスタム管理ページの保存処理にリファラ情報を利用します。

<form method="post" action="options.php">
    <?php settings_fields('my_option_group'); ?>
    <?php wp_referer_field(); ?>
    <input type="text" name="my_option" value="値" />
    <button type="submit">保存</button>
</form>

例5: Ajaxリクエストとの統合

Ajaxリクエスト送信時にリファラ情報を埋め込む例です。

<form id="ajax-form" method="post" action="">
    <?php wp_referer_field(); ?>
    <input type="text" name="ajax_data" />
    <button type="button" id="ajax-submit">送信</button>
</form>
<script>
document.getElementById('ajax-submit').addEventListener('click', function() {
    var formData = new FormData(document.getElementById('ajax-form'));
    fetch('admin-ajax.php', {
        method: 'POST',
        body: formData
    }).then(response => response.text())
    .then(data => console.log(data));
});
</script>

注意点

  • wp_referer_field()は、CSRF(クロスサイトリクエストフォージェリ)攻撃を防ぐために他のセキュリティ機能と併用する必要があります。
  • このフィールドを信頼性のある環境でのみ使用してください。
  • リファラ情報が意図したURLに一致することを必ず検証してください。

関連機能: