wp_ajax_my_action
は、プラグインに置かれている場合にのみ機能します。テーマのfunctions.phpのAJAXアクション
私のテーマのfunctions.phpでそれを実行することができるかどうか知っていますか?
wp_ajax_my_action
は、プラグインに置かれている場合にのみ機能します。テーマのfunctions.phpのAJAXアクション
私のテーマのfunctions.phpでそれを実行することができるかどうか知っていますか?
はい、できます:
ページ・テンプレートで:あなたのfunctions.php内
var AjaxUrl = '<?php echo admin_url('admin-ajax.php'); ?>';
$.ajax({
type: "POST",
url: AjaxUrl,
data: {
action: 'your_action'
},
:
function your_action() {
//write your code here
}
add_action('wp_ajax_your_action', 'your_action');
add_action('wp_ajax_nopriv_your_action', 'your_action');
パスアクションHTMLフォーム内
<form name="myform">
<input type="hidden" name="action" value="custom_action">
<input type="text" name="get_first_name" >
<input type="submit value="submit">
</form>
あなたjQueryはこのように見える
機能ファイルにこのコードを入れ<script>
jQuery(document).ready(function()
{
var $this = jQuery(this); // Cache this
jQuery.ajax({
url: '<?php echo admin_url("admin-ajax.php") ?>', // Let WordPress figure this url out...
type: 'post',
dataType: 'JSON', // Set this so we don't need to decode the response...
data: $this.serialize(), // One-liner form data prep...
beforeSend: function() {
// You could do an animation here...
},
success: function (data)
{
if (data.status === 'success') {
alert("Success");
// Here, you could trigger a success message
} else {
// fail
}
}
});
});
</script>
function custom_action_function()
{
$first_name = $_POST['get_first_name'];
/* fetch your form variable here */
if('your condition') // your condition if success
{
echo json_encode(array('status' => 'success', 'message' => 'Message Sent.'));
exit;
}
else
{
echo json_encode(array('status' => 'error', 'message' => 'Message not sent'));
exit;
}
}
add_action('wp_ajax_custom_action', 'custom_action_function'); // Call when user logged in
add_action('wp_ajax_nopriv_custom_action', 'custom_action_function'); // Call when user in not logged in
申し訳ありませんが、私は自分自身を間違って表現しました。 Ajax関数をfunctions.phpに追加することは完全に機能しますが、それを私のテーマの別のファイルに追加しても機能しません。ファイルはfunctions.phpに含まれています –
申し訳ありませんが、私は自分が間違って表明しました。 Ajax関数をfunctions.phpに追加することは完全に機能しますが、それを私のテーマの別のファイルに追加しても機能しません。ファイルはfunctions.phpに含まれています –