我是wordpress插件开发的新手,面临下面的插件测试问题。该插件使用短代码,当点击搜索按钮时,jquery将触发对admin-ajax.php的ajax调用。
问题: 如果我只是以管理员身份登录,则会调用get_result。它将显示Match Found或No Match Found。 如果没有登录,它将返回0
请帮助,谢谢先进
function wp_search_scripts() {
// Your actual AJAX script
wp_enqueue_script( 'myAjax', plugins_url( 'custom.js', __FILE__ ), array( 'jquery' ) );
// This will localize the link for the ajax url to your 'my-script' js file (above). You can retreive it in 'custom.js' with 'myAjax.ajaxurl'
wp_localize_script( 'myAjax', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
}
add_action( 'wp_enqueue_scripts', 'wp_search_scripts' );
function search()
{
global $wpdb;
$table_name = $wpdb->prefix . "searching";
// will return NULL if there isn't one
if ( $wpdb->get_var('SHOW TABLES LIKE ' . $table_name) != $table_name )
{
$sql = 'CREATE TABLE ' . $table_name . '(id INTEGER(10) UNSIGNED AUTO_INCREMENT, name VARCHAR(1), PRIMARY KEY (id) )';
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
add_option('search_mydatabase_version','1.0');
}
}register_activation_hook(__FILE__,'search');
function search_now() {
$temp = "<input type='text' id='txtsearch' name='txtsearch' style='border:1px solid #000;padding:4px 8px;width:350px;'/>";
$temp .= "<input type='submit' id='getResult' Value='Search' style='background:#f00;color:#fff;padding:4px 15px;border:none;margin:-10px 10px 0px 10px;'/>";
$temp .= "<br /><div id='result'></div>";
return $temp;
}add_shortcode("search-now", "search_now");
add_action('wp_ajax_get_result', 'get_result');
add_action('wp_ajax_nopriv_get_result', 'get_result');
function get_result() {
$txtVal = $_POST['txtVal'];
if(!$txtVal)
{
$results .= "<h4>Match Found</h4>";
}else {
$results .= "<h4>No Match Found</h4>";
}
}
javascript文件
jQuery(document).ready(function() {
jQuery("#getResult").click(function(){
var txtVal = jQuery("#txtsearch").val();
alert(txtVal);
jQuery.ajax({
type: 'POST',
url: '/wordpress4/wp-admin/admin-ajax.php',
data: {
action: 'get_result',
txtVal: txtVal,
},
success: function(data, textStatus, XMLHttpRequest){
jQuery("#result").html('');
jQuery("#result").append(data);
},
error: function(MLHttpRequest, textStatus, errorThrown){
alert(errorThrown);
}
});
});
});
答案 0 :(得分:0)
你的get_result函数应该是
function get_result() {
if( is_admin() ) { // checks that current user is admin
$txtVal = $_POST['txtVal'];
if(!$txtVal) {
$results = "<h4>Match Found</h4>";
}else {
$results = "<h4>No Match Found</h4>";
}
} else {
$results = "not ad admin";
}
echo $results;
die();
}