워드프레스에서 AJAX를 이용한 폼 처리 플러그인을 작성하는 예
https://codex.wordpress.org/AJAX_in_Plugins
개요
WordPress에서 AJAX를 사용하는 방법은 사용하는 영역에 따라서 2가지 방법으로 구분된다
관리자 패널에서 등록한 메뉴에서 AJAX 요청을 하는 경우와 일반 이용자 화면에서 AJAX를 사용하는 방법이 약간 다르다
여기서는 일반 이용자 화면에서 AJAX를 사용하는 절차에 대하여 알아본다
Shortcode를 통해 폼과 AJAX 기능을 페이지에 추가하고 이용자가 AJAX 요청을 전송하면 서버측으로 전달된 파라미터를 통해 동적으로 액션을 실행하고 그 결과를 JSON 형식 문자열로 클라이언트에게 응답하는 예제이다
Nonce에 대한 설명 : https://codex.wordpress.org/Function_Reference/wp_create_nonce
일반적인 플러그인을 작성하는 방법을 사용하므로 아래의 php 코드는 wp-content/plugins/ 안에 임의의 파일명으로 저장하면 된다
이 플러그인 코드는 1개의 Shortcode 함수와 1개의 액션함수로 구성되어 있다.
Shortcode 함수는 웹페이지에 폼과 AJAX기능이 포함되도록 기능하고, 액션함수는 AJAX요청을 처리하고 JSON으로 응답하는 기능으로 구성되어 있다
원문 참조 : http://solislab.com/blog/5-tips-for-using-ajax-in-wordpress/
<?php /* Plugin Name: Simple AJAX Demo Plugin Plugin URI: http://micropilot.tistory.com Description: AJAX 요청으로 서버측 스크립트를 실행하고 응답을 수신하는 플러그인 샘플 [my_ajax_plugin_demo] Version: 1.0 */ // wp_create_nonce(), wp_verify_nonce()함수를 찾지 못하는 경우 아래의 행이 반드시 필요함 require_once(ABSPATH .'wp-includes/pluggable.php'); // embed the javascript file that makes the AJAX request wp_enqueue_script( 'my-ajax-request', plugin_dir_url( __FILE__ ) . 'js/ajax.js', array( 'jquery' ) ); // declare the URL to the file that handles the AJAX request (wp-admin/admin-ajax.php) 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' ), ) ); /** 다음과 같은 Shortcode를 사용하여 화면에 폼을 출력한다 [my_ajax_plugin_demo] */ function show_simple_ajax_form(){ ?> <script> jQuery(function(){ alert('jQuery ready!'); jQuery('#submitBtn').on('click', function(){ jQuery.post( // see tip #1 for how we declare global javascript variables MyAjax.ajaxurl, { // here we declare the parameters to send along with the request // this means the following action hooks will be fired: // wp_ajax_nopriv_myajax-submit and wp_ajax_myajax-submit action : 'myajax-submit', // other parameters can be added along with "action" postID : 'the_post_id', // send the nonce along with the request postCommentNonce : MyAjax.postCommentNonce, }, function( response ) { alert( '성공여부='+response.success ); } ); // end of post }); // end of on click }); // end of ready </script> <form id="form1"> <button id='submitBtn' type="button">요청</button> </form> <?php } // [my_ajax_plugin_demo] 코드를 사용한 페이지에서는 폼과 AJAX 기능이 포함된다 add_shortcode('my_ajax_plugin_demo','show_simple_ajax_form'); // 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' ); // 위에서 'wp_ajax_myajax-submit' 후크에 myajax_submit()함수가 등록되어 있는 상태에서 // AJAX요청이 오면 admin-ajax.php에서 요청을 받고 do_action('wp_ajax_myajax-submit')호출 // 하므로 myajax_submit() 가 실행되어 AJAX 요청을 처리할 수 있다 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!'); // ignore the request if the current user doesn't have // sufficient permissions if ( current_user_can( 'edit_posts' ) ) { // get the submitted parameters $postID = $_POST['postID']; wp_send_json( array( 'success' => true ) ); }else{ wp_send_json( array( 'success' => false) ); } // IMPORTANT: don't forget to "exit" exit; } ?>