您提供的第一个块可以充分更新,以便与代码一起使用,但请参见下面的示例:
首先,设置WordPress函数以加载脚本(在functions.php中),并设置全局ajax脚本变量以供以后使用。我将其分为几个部分,因为这样做是正确的:
function js_enqueue_scripts() {
wp_enqueue_script("my-ajax-handle", get_stylesheet_directory_uri() . "/assets/js/ajax.js", array(\'jquery\'));
//the_ajax_script will use to print admin-ajaxurl in custom ajax.js
wp_localize_script(\'my-ajax-handle\', \'the_ajax_script\', array(
\'ajaxurl\' => admin_url(\'admin-ajax.php\'), \'_nonce\' => wp_create_nonce(\'my-ajax-handle-nonce\')
));
}
add_action("wp_enqueue_scripts", "js_enqueue_scripts");
之后,您可以将以下内容添加到函数中。php,这将用于前端ajax请求。
nopriv
管理请求不需要。
add_action(\'wp_ajax_nopriv_load_more_post_ajax\', \'load_more_post_ajax\');
add_action(\'wp_ajax_load_more_post_ajax\', \'load_more_post_ajax\');
以上部分是ajax函数的唯一标识符,必须在其中发送数据才能进行处理并从中返回响应。
接下来,让我们构建php函数来处理我们刚才请求的请求:
/**
* Load more posts using ajax.
*/
function load_more_post_ajax() {
if (wp_verify_nonce($_REQUEST[\'security\'], \'my-ajax-handle-nonce\') === false) {
wp_send_json_error();
wp_die(\'Invalid Request!\');
}
$ppp = $_POST[\'ppp\'] ?? 1;
$page = $_POST[\'pageNumber\'] ?? 0;
$loop = new \\WP_Query([
\'suppress_filters\' => true, \'post_type\' => \'post\', \'posts_per_page\' => $ppp, \'paged\' => $page,
]);
if ($loop->have_posts()) {
while ($loop->have_posts()) : $loop->the_post();
echo "<div><h1>\' . get_the_title() . \'</h1>\' . get_the_content() . \'</div>";
endwhile;
}
wp_reset_postdata();
wp_die(); // This must always be here, this will close to process.
}
最后,我们将在新文件中创建JQuery
ajax.js
:
jQuery(document).ready(function () {
jQuery(\'#load-more\').on(\'click\', function () { //Use on operator for dom loading ease
var $this = jQuery(this); // This is the button object
var data = {}; // Create an Object to add variables to later if we change them
data.action = \'load_more_post_ajax\'; // Refer to action
data.page = 2; //Add whatever else you want
data.security = the_ajax_script._nonce;
$this.html(\'Loading...\'); // Change the wording on click.
jQuery.ajax({
url: the_ajax_script.ajaxurl,
type: \'post\',
data: data,
success: function (response) {
$this.html(\'Load More\'); // Change the wording back on success.
if (response !== \'\') {
$(\'.testimonials\').append(response);
page++;
} else {
$(\'.load-more-posts\').hide();
}
},
error: function (jqXHR, textStatus, errorThrown) {
$loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
});
});
你可以选择这些选项,可能性是无穷的。