WordPress/AJAX example

Wordpress AJAX example

Soul-Learner 2016. 2. 25. 19:24

워드프레스에서 AJAX 사용하는 예


wp-content/plugins/love-plugins/register_process.css

/* register_process.css */
div.excerptContainer { border:1px solid lightgray; border-radius:10px; padding:15px;}
ul { padding:5px; }
li {/*list-style-type:circle; background:#cceeff;*/ padding:5px;}
img.excerptImg {display:block; text-align:center; margin:0px auto; width:auto; height:auto; max-width:300px; max-height:200px;}
img.excerptImg2 {display:block; text-align:center; margin:0px auto; width:auto; height:auto; max-width:500px; max-height:400px;}


wp-content/plugins/love-plugins/ajax_register_request.js

/* ajax_register_request.js */
jQuery(function(){
	jQuery('#btnSave').on('click',function(){
		if(!confirm('선택된 이용자를 등록처리하시겠어요?')) return;
		ajax_request();
	});
});

function ajax_request(){
	var url = localdata.ajaxurl;
	var nonce = localdata.theNonce;
	var form_data = jQuery('#form1').serializeArray();
	form_data.push({name: 'theNonce', value: nonce});
	//alert(url+'\n'+nonce+'\n'+form_data);
	jQuery.post( url,
		form_data,
		function(data, textStatus, jqXHR){
			if(data.success){
				location.reload(true);
				alert("이용자 등록처리에 성공했습니다"); 
			}
			else { alert("이용자 등록처리에 실패했습니다"); }
		},
		"json"
	).fail (function(jqXHR, textStatus, errorThrown) {
	  alert("에러:"+errorThrown);
	});
}


wp-content/plugins/love-plugins/my_plugin.php

<?php
/*
Plugin Name: Plugin-for-Excerpts
Plugin URI: http://micropilot.tistory.com
Description: A real simple plugin [shortcode_for_excerpt] [getTitle_mb_Notice_To_All]
Version: 1.0
Author: Kim Chang Woon
Author URI: http://micropilot.tistory.com
*/
 
// wordpress.org 사이트에 올려졌을 때 이 파일에 직접 접근하는 것을 방지한다
defined( 'ABSPATH' ) or die( 'Plugin file cannot be accessed directly.' );

// wp_create_nonce(), wp_verify_nonce()함수를 찾지 못하는 경우 아래의 행이 반드시 필요함
require_once(ABSPATH .'wp-includes/pluggable.php');

add_action( 'wp_enqueue_scripts', 'ajax_enqueue_scripts' );
function ajax_enqueue_scripts() {
	wp_enqueue_script( 'user-register-request', plugins_url( '/ajax_register_request.js',__FILE__ ), array( 'jquery' ) );

	wp_enqueue_style( 'user-register-request', plugins_url('/register_process.css', __FILE__ ) );

	wp_localize_script( 'user-register-request', 'localdata', array(
	 'ajaxurl' => admin_url( 'admin-ajax.php' ),
	 'theNonce' => wp_create_nonce( 'register-request-nonce' ),
	 )
	);
}
/*
function display_msg($atts) {
    echo 'Shortcode 플러그인에서 생성한 Excerpt(요약) 메시지<p>';
}

// 테스트용 Shortcode 태그를 선언한다. 선언된 태그는 페이지 요약란에 사용할 수 있다
//[shortcode_for_excerpt] 라는 Shortcode 태그를 페이지 편집화면의 요약(Excerpts)란에 입력하면 된다
//
add_shortcode('shortcode_for_excerpt', 'display_msg');
*/
/* 
MangBoard에서 첨부파일 정보를 저장하는 테이블 : mb_files
mb_files 테이블의 속성:
pid, user_pid, user_name, board_name, board_pid, table_name, file_name, file_path, file_sequence
file_path 컬럼에 저장된 경로는 아래의 URL에 포함된 'mb-file.php?path=' 이후의 문자열이다.
웹브라우저 화면에 이미지를 출려하려면 아래처럼, mb_files 테이블의 file_path 컬럼에 저장된 경로를 urlencode()함수로 변환하여 사용해야 한다
<img src="http://loveridgepre.net/wp-content/plugins/mangboard/includes/mb-file.php?path=2016%2F02%2F21%2FF3_KakaoTalk_20160217_%ED%94%84%EB%A6%AC%EC%8A%A4%EC%BF%A8%EB%A1%9C%EA%B3%A0_small.jpg" http://loveridgepre.net/2016%2F02%2F21%2FF3_KakaoTalk_20160217_%ED%94%84%EB%A6%AC%EC%8A%A4%EC%BF%A8%EB%A1%9C%EA%B3%A0_small.jpg
*/

// Shortcode 함수, 요약란에 입력한 Shortcode에 의해 호출되어 글의 제목과 특성 이미지를 가져옴
// Excerpt입력란에 사용하는 방법[get_excerpts_title_img table_name='mb_Notice_To_All']

add_shortcode('get_excerpts_title_img', 'getExcerpts');

function getExcerpts($atts) {
	$arr_page_id = array(
		'mb_Notice_To_All'=>'54',
		'mb_BBS_For_All'=>'56',
		'mb_Notice_To_SEED'=>'46',
		'mb_Notice_To_TREE1'=>'30',
		'mb_Notice_To_TREE2'=>'38',
		'mb_Notice_To_FRUIT1'=>'34',
		'mb_Notice_To_FRUIT2'=>'42',
		'mb_Notice_To_DAYCARE'=>'50'
	);

	$arr_pid = array();
	$arr_title = array();
	
	$rows = 5;
	if($atts['table_name']=='mb_Notice_To_All' ||
		$atts['table_name']=='mb_BBS_For_All') {
			$rows = 10;
	}
	
	global $wpdb;
	$sql = "SELECT pid, title FROM ".$atts['table_name']." ORDER BY pid DESC LIMIT 0, $rows";
	$rs = $wpdb->get_results($sql);
	
	foreach($rs as $notice){
		array_push($arr_pid, $notice->pid);
		array_push($arr_title, $notice->title);
	}
	
	$arr_imgpath = getFeatureImg($atts['table_name'], $arr_pid);
	
	$cssClass = "excerptImg";
	if($atts['table_name']=='mb_Notice_To_All') {
		$cssClass = "excerptImg2";
		echo '<h6>[전체 공지]</h6>';
	}else if($atts['table_name']=='mb_BBS_For_All') {
		$cssClass = "excerptImg2";
		echo '<h6>[전체 게시판]</h6>';
	}
	echo "<div class='excerptContainer'><ul>";
	$img_dir = "http://loveridgepre.net/wp-content/plugins/mangboard/includes/mb-file.php?path=";
	for($i=0;$i<count($arr_pid);$i++){
		$title = $arr_title[$i];
		echo "<li><a href='http://loveridgepre.net/?page_id=".$arr_page_id[$atts['table_name']]."'>".$title;
		if($arr_imgpath[$arr_pid[$i]]!=null){
			echo "<img class='".$cssClass."' src='".$img_dir.urlencode($arr_imgpath[$arr_pid[$i]])."'>";
		}
		echo "</a></li>";
	}
	echo "</ul></div>";
}

/* 각 공지게시판의 최근 공지에 포함된 이미지 읽어오기*/
function getFeatureImg($table_name, $arr_pid) {
	$arr_imgpath = array();
	global $wpdb;
	$sql = "SELECT board_pid, file_path ".
	"FROM mb_files ".
	"WHERE table_name='".$table_name."' ".
	"AND board_pid BETWEEN ".$arr_pid[count($arr_pid)-1]." AND $arr_pid[0] ".
	"AND file_sequence=1 ".
	"ORDER BY board_pid DESC ".
	"LIMIT 0, 1";
	$rs = $wpdb->get_results($sql);
	foreach($rs as $record){
		$arr_imgpath[$record->board_pid] = $record->file_path;
	}
	return $arr_imgpath;
}

/* 관리자의 회원가입 승인 절차, user_level 값이 0,1인 이용자를 선택하여 폼에 보여준다 */
add_shortcode('get_new_comer', 'admin_approval01');
function admin_approval01(){
	$user_level = get_user_meta(get_current_user_id(), 'wp_user_level', true);
	//error_log("사용자 레벨:".((int)$user_level+5));
	if(((int)$user_level)<10) return;
	global $wpdb;
	$sql = "SELECT u.ID, u.user_login, u.user_email, u.user_registered, ".
	"um.meta_key, um.meta_value msg, mu.user_level AS level ".
	"FROM wp_users u ".
	"INNER JOIN wp_usermeta um ".
	"ON u.ID=um.user_id ".
	"AND um.meta_key='user_desc' ".
	"INNER JOIN mb_users mu ".
	"ON u.ID=mu.wp_user_pid ".
	"AND (mu.user_level=1 OR mu.user_level=0)";

	$rs = $wpdb->get_results($sql);
?>
	<form name="form1" id="form1">
	<input type="hidden" name="action" value="reg_approve_submited">
	<table>
	
	<tr><th>No</th><th>Email</th><th>Registered</th><th>Message</th><th>Level</th><th>Approve</th></tr>
<?php
	foreach($rs as $user) {
		echo "<tr><td>".$user->ID."</td><td>".$user->user_email."</td>".
		"<td>".$user->user_registered."</td><td>".$user->msg."</td><td>";
		echo "<select name='".$user->ID."-newLevel'>";
		//error_log("사용자 레벨:".$user->level);
			for($i=0;$i<=10;$i++){
				echo "<option ";
				echo ($user->level==$i) ? 'selected ':'';
				echo "value='".$i."'>$i</option>";
			}
		echo "</select></td>".
		"<td><input type='checkbox' name='approved[]' value='".$user->ID."'></td>".
		"</tr>";
	}
?>
	</table>
	<div style="width:100%; display:inline-block; text-align:right;">
	<button type="reset" style="background:orange;">취 소</button>
	<button id="btnSave" type="button">등록처리</button>
	</div>
	</form>
<?php
}

add_action( 'wp_ajax_nopriv_reg_approve_submited', 'update_user_level' );
add_action( 'wp_ajax_reg_approve_submited', 'update_user_level' );

// AJAX 요청에 대한 처리 및 응답(json)
function update_user_level(){
	$nonce = $_POST['theNonce'];

	if ( ! wp_verify_nonce( $nonce, 'register-request-nonce' ) )
		die ( 'Busted!');

	if(!isset($_POST['approved'])) {
		die();
	}
	$arr_approve = $_POST['approved'];

	global $wpdb;
	$updated = true;
	foreach($arr_approve as $num){
		$new_level = $_POST[$num."-newLevel"];
		$updated = $wpdb->update( 
			'mb_users', 
			array( 'user_level' => $new_level),	// data
			array( 'wp_user_pid' => $num), 		// where
			array( '%s'), 						// data format
			array( '%s' ) 						// where format
		);
		if(!$updated) {
			break;
		}
	}
	$response = array('success'=>$updated);
	wp_send_json($response);
}
?>