要在WordPress网站中使用AJAX,您可以通过管理AJAX。php文件。此文件处理您的请求并将其发送到正确的函数。
关于如何实现以下目标的简短分步指南:
首先,您需要本地化javascript文件,以便它知道管理ajax的URL。服务器上的php文件。
add_action( \'wp_enqueue_scripts\', \'wpse_229573_localize\' );
function wpse_229573_localize() {
wp_localize_script( \'FILE_HANDLER\', \'ajax\', array( \'url\' => admin_url( \'admin-ajax.php\' ) ) );
}
其中FILE\\u HANDLER是将脚本排入队列时使用的句柄。
现在,在这个javascript文件中,您可以用不同的方式进行AAX调用,下面是一种可能性
jQuery.ajax( {
url: ajax.url, //The ajax object is populated in this script thanks to the wp_localize_script function. ajax.url containts the url to your admin-ajax.php file.
type:\'POST\',
data: {
action: \'wpse_229573_ajax_callback\', // This action is important as it determines which functions are called
post_type: jquery( \'#post-type\' ).val(), // Here you can send the post type set by the visitor, this would be a <select> with id="post-type" for example
},
success: function( data ) {
// On a succesful return \'data\' contains whatever you have echoed in the ajax function
console.log( data );
// Here you can manually open a lightbox with the correct data if you want, for the correct code to you that you need to check the documentaiton of your chosen lightbox plugin
}
});
在任何PHP文件中,理想情况下都是一个插件,但它可以是您的
functions.php
此外,您还为WordPress添加了一个操作来处理AJAX调用。您需要两个,一个用于管理员,另一个用于非管理员(否则,如果假设您想要测试,并且您以管理员身份登录,那么它将不起作用)
// Notice the wpse_229573_ajax_callback after both wp_ajax and wp_ajax_nopriv
// These correspond with the action you\'ve set in the javascript file making the AJAX call.
// This is how WordPress knows what PHP code to run on the AJAX call.
add_action( \'wp_ajax_wpse_229573_ajax_callback\', \'wpse_229573_ajax_function\' );
add_action( \'wp_ajax_nopriv_wpse_229573_ajax_callback\', \'wpse_229573_ajax_function\' );
// This is the function that both actions above call
// The data that you\'ve send in the AJAX call is availble as either $_POST or $_GET depending on the call
// In this example it\'s $_POST
function wpse_229573_ajax_function() {
// We added post_type to the AJAX call as data, now we\'re echoing that back.
// You can also choose to json_encode() data before you echo and parse the JSON in your javascript file.
echo $_POST[\'post_type\'];
wp_die();
}