2017-01-26 56 views
3

我有一個WordPress網站,我將其配置爲使用jQuery/AJAX來查詢和加載div框內的帖子。WP AJAX:nonce在註銷時工作,但在登錄時不工作

下面是我在functions.php(大量簡化,自然):

function mysite_enqueue_scripts() { 
    wp_register_script('mysite_front' , get_bloginfo('template_url') . '/js/front.js' , array('jquery')); 
    wp_enqueue_script('mysite_front'); //loads the front-side jquery 
    wp_localize_script('mysite_front' , 'AJAX' , array( 
    'ajaxurl' => admin_url('admin-ajax.php') , 
    'nonce' => wp_create_nonce('mysite-ajax-nonce') 
)); //localizes the script 
} 
add_action('wp_enqueue_scripts' , 'mysite_enqueue_scripts' , 100); 
add_action('wp_ajax_nopriv_load_items' , 'mysite_ajax_load_items'); 
add_action('wp_ajax_load_items' , 'mysite_ajax_load_items'); 

function mysite_ajax_load_items() { 
    if(!check_ajax_referer('mysite-ajax-nonce' , 'nonce' , false)) { 
    wp_send_json(array('error' => 'nonce error')); 
    return; 
    } else { 
    [[[all the WP query stuff goes here and creates an $html string]]] 
    wp_send_json(array('html' => $html)); 
    } 
} 

jQuery的front.js

jQuery(document).ready(function($) { 
    $('#mysite-load').click(function() { 
    var postData = { 
     action : 'load_items' , 
     nonce : AJAX.nonce 
    }; 
    jQuery.post(
     AJAX.ajaxurl , postData , function(response) { 
     if(typeof(response['html']) !== 'undefined') { 
      $('#mysite-load').html(response['html']); 
     } else if(typeof(response['error']) !== 'undefined') { 
      $('#mysite-load').html('Error: ' + response['error']); 
     } 
     } 
    ); 
    }); 
}); 

的HTML:

<div id="mysite-load">click</div> 

當我不在登錄到該網站的wp-admin並加載此頁面,一切正常。

但是,當我登錄到該網站的wp-admin並加載此頁面時,它將返回'nonce error'錯誤,而不是它應該加載的HTML。

該問題不是瀏覽器特定的;嘗試在Safari和Chrome中都收到相同的錯誤。我也嘗試使用wp_verify_nonce()而不是check_ajax_referer(),並且收到了相同的結果。

任何想法爲什麼會發生這種情況?

回答

0

我完全是這個問題。我發現問題在於,對於API AJAX請求,以特定方式處理隨機數。在我的情況下,這是使用自定義端點,但我想這對任何API調用都是一樣的。

相關文檔在這裏:https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/。感興趣的特定段落在Cookie認證下:

對於開發者進行手動Ajax請求,隨機數將需要爲 傳遞給每個請求。 API使用隨機數,動作設置爲 wp_rest。然後可以通過參數_wpnonce數據 (POST數據或查詢GET請求)或通過X-WP-Nonce標頭將其傳遞給API。

在實踐中,我發現,這意味着你必須在以最小的使用與設置爲「WP-休息」的行動隨機數以確保登錄用戶是否正確裝入在API請求上下文。否則,您將使用登錄用戶生成您的自定義隨機數,但嘗試使用匿名用戶進行驗證(除非使用此隨機數,否則這是API調用的默認值)。

$nonce = wp_create_nonce('wp_rest'); 

還那麼就需要確保你生成隨機數與這一行動是通過X-WP-杜撰頭返回。

$.ajax({ 
    type: 'POST', 
    url: your-api-url-here, 
    contentType: 'application/json; charset=UTF-8', 
    beforeSend: function(jqXhr) { 
    jqXhr.setRequestHeader('X-WP-Nonce', nonce) 
    }, 
    data: your-data-here 
}) 

(爲了清楚起見,我離開了腳本的本地化配件爲現時轉移到JavaScript的背景下,但你必須在那些你的問題,所以我假定這是所有罰款)

一旦你已經完成了這項工作,您的AJAX調用將不再是匿名的(如果您已登錄),並且您的其他現時值現在可以正確驗證。