ターゲット URL の把握
WordPress では、すべての AJAX リクエストを次の URL に対して行う必要があります。
http://www.example.com/wp-admin/admin-ajax.php
プラグインまたはテーマ ディレクトリにあるファイルに対して直接 AJAX リクエストを行うべきではありません。
また、上記の URL をハードコーディングしないでください。代わりに、次の関数を使用して URL を作成する必要があります。
<script>
ajax_url = "<?php echo admin_url('admin-ajax.php'); ?>";
</script>
上記の代わりに を使用できますwp_localize_script()
が、これは必須ではありません。上記も問題ありません。
注: 「管理者」の部分は気にしないでください。この URL は、ログインしていない (ゲスト) ユーザーを含むすべてのユーザーが使用する正しい URL です。
AJAX リクエストに使用する関数を WordPress に伝える
AJAX リクエストを処理する関数を WordPress に知らせる必要があります。
そのために、カスタム関数を作成し、wp_ajax_*
およびwp_ajax_nopriv_*
フックを使用して登録します。
add_action('wp_ajax_mycustomfunc', 'mycustomfunc'); // Logged-in users
add_action('wp_ajax_nopriv_mycustomfunc', 'mycustomfunc'); // Guest users
function mycustomfunc() {
$whatever = esc_html($_POST['whatever']);
echo 'It works: '.$whatever;
exit; // This is required to end AJAX requests properly.
}
AJAX リクエストでも「mycustomfunc」を指定することを忘れないでください
最後に、適切な AJAX リクエストを作成する方法を次に示します。
(function ($) {
$(document).ready(function () {
var my_data = {
action: 'mycustomfunc', // This is required so WordPress knows which func to use
whatever: "yes it is" // Post any variables you want here
};
jQuery.post(ajax_url, my_data, function(response) {
alert('Got this from the server: ' + response);
});
});
})(jQuery);
すべてを組み合わせる
すべてを 1 つのファイルに入れる必要がある場合は、次のようにします。
// Register my custom function for AJAX processing
add_action('wp_ajax_mycustomfunc', 'mycustomfunc'); // Logged-in users
add_action('wp_ajax_nopriv_mycustomfunc', 'mycustomfunc'); // Guest users
function mycustomfunc() {
$whatever = esc_html($_POST['whatever']);
echo 'It works: '.$whatever;
exit; // This is required to end AJAX requests properly.
}
// Inline JavaScript
add_action('wp_footer', 'my_inline_js');
function my_inline_js() { ?>
<script>
// Set the "ajax_url" variable available globally
ajax_url = "<?php echo admin_url('admin-ajax.php'); ?>";
// Make your AJAX request on document ready:
(function ($) {
$(document).ready(function () {
var my_data = {
action: 'mycustomfunc', // This is required so WordPress knows which func to use
whatever: "yes it is" // Post any variables you want here
};
$.post(ajax_url, my_data, function(response) { // This will make an AJAX request upon page load
alert('Got this from the server: ' + response);
});
});
})(jQuery);
</script>
<?php
}
注: このajax_url
部分については、手動で設定する代わりに使用できますがwp_localize_script()
、エンキューされた既存のスクリプトを指定する必要があるため、柔軟ではありません。
注: また、インライン JavaScript を手動でページに出力するには、wp_footer
フックを使用するのが適切です。使用する場合は、代わりにフックwp_localize_script()
を使用します。wp_enqueue_scripts