http://www.garyc40.com/2010/03/5-tips-for-using-ajax-in-wordpress/をガイドとして使用して、ユーザーが情報を入力するためのフォームを作成し、投稿を作成しますカスタム投稿タイプの内部。アラートの長い文字列が表示されますが、サーバーからは常に「0」の応答が返されます。これについて何か助けはありますか?
私のプラグインファイルphp:
function ajaxurl() {
wp_enqueue_script( 'my-ajax-request', plugin_dir_url( __FILE__ ) . 'js/ajax.js', array( 'jquery' ) );
wp_localize_script( 'my-ajax-request', 'MyAjax', array(
// URL to wp-admin/admin-ajax.php to process the request
'ajaxurl' => admin_url( 'admin-ajax.php' ),
// generate a nonce with a unique ID "myajax-post-comment-nonce"
// so that you can check it later when an AJAX request is sent
'postCommentNonce' => wp_create_nonce( 'myajax-post-comment-nonce' ),
)
);
}
add_action('wp_head', 'ajaxurl');
// if both logged in and not logged in users can send this AJAX request,
// add both of these actions, otherwise add only the appropriate one
add_action( 'wp_ajax_nopriv_myajax-submit', 'myajax_submit' );
add_action( 'wp_ajax_myajax-submit', 'myajax_submit' );
function myajax_submit() {
$nonce = $_POST['postCommentNonce'];
// check to see if the submitted nonce matches with the
// generated nonce we created earlier
if ( ! wp_verify_nonce( $nonce, 'myajax-post-comment-nonce' ) )
die ( 'Busted!');
// get the submitted parameters
$postID = $_POST['postID'];
if ( isset($_post['post_ID']) ) {
};
//Create Post from post data
$newpost = array(
'post_title' => $_POST['title'],
'post_author' => $_POST['author'],
'post_type' => 'assets',
'post_content' => $_POST['description'],
'post_category' => $_POST['category']
);
//Actually Create the post
$post_id = wp_insert_post($newpost);
//now that we have an ID we can add the post meta
update_post_meta($post_id ,'key', $_POST['key']);
update_post_meta($post_id ,'assetname', $_POST['assetname']);
update_post_meta($post_id ,'assetadd1', $_POST['assetadd1']);
update_post_meta($post_id ,'assetadd2', $_POST['assetadd2']);
update_post_meta($post_id ,'assetcity', $_POST['assetcity']);
update_post_meta($post_id ,'assetstate', $_POST['assetstate']);
update_post_meta($post_id ,'assetzipcode', $_POST['assetzipcode']);
update_post_meta($post_id ,'assetlocation', $_POST['assetlocation']);
// generate the response
$response = json_encode( array( 'success' => true ) );
// response output
header( "Content-Type: application/json" );
echo $response;
die();
// IMPORTANT: don't forget to "exit"
exit;
}
My jQuery: $(document).ready ピースを追加しない限り、何らかの理由で jquery が起動しません
$(document).ready(function () {
jQuery('#myForm').submit(function() {
data = $(this).serialize();
data = data + "&postCommentNonce=" + MyAjax.postCommentNonce + "&action=myajax_submit";
alert( data );
この時点まで、すべてが機能しています。フォーム入力フィールドから長い入力文字列を取得します
jQuery.post(
MyAjax.ajaxurl,
data,
function( response ) {
alert( response );
}
);
return false;
});
});
結局、サーバーから毎回「0」の応答しか得られません。これに関するヘルプは大歓迎です。