【发布时间】:2017-02-15 12:46:56
【问题描述】:
我正在尝试使用 AJAX 加载我的帖子,并且加载的帖子具有基于 ajax 的帖子导航。
我的问题是:我应该如何将帖子分页设置为帖子页脚。 (如果很难理解我的意思,请查看linked image)。因此,当您从当前打开的帖子的页脚导航时,您会直接打开上一个或下一个项目,它将打开到与您导航的项目相同的 div#single-project。
我可以使用相同的functions.php函数来发送分页数据,还是应该创建一个新函数来发送分页数据。
functions.php
add_action( 'wp_ajax_load_post', 'working_function' );
add_action( 'wp_ajax_nopriv_load_post', 'working_function' );
function working_function() {
check_ajax_referer( 'nonce', 'security' );
if ( isset( $_POST['id'] )
&& 'post' == get_post_type( $_POST['id'] )
&& 'publish' == get_post_status( $_POST['id'] ) ) {
$id = (int)$_POST['id'];
global $post;
$post = get_post( $id );
$prev_post = get_previous_post();
$next_post = get_next_post();
$data = array();
$data['article'] = '<h1>' . apply_filters( 'the_title', $post->post_title ) . '</h1>';
$data['article'] .= apply_filters( 'the_content', $post->post_content );
$data['article'] .= '<footer>' . '<nav class="navigation pagination">' . '<div class="nav-links">' . '<div class="nav-previous">' . '<a nav-id=""' . 'href="' . apply_filters('the_permalink', get_permalink($prev_post->ID)) . '" rel="prev">Previous Article</a>' . '</div>' . '<div class="nav-next">' . '<a href="' . apply_filters('the_permalink', get_permalink($next_post->ID)) . '" rel="prev">Next Article</a>' . '</div' . '</div>' . '</nav>' . '</footer>';
wp_send_json_success($data);
} else {
wp_send_json_error( 'Error' );
}
wp_die();
}
主要js:
jQuery(function ($) {
"use strict";
$(document).ready(function () {
$(document).on('click', 'a.link-to', function (event) {
event.preventDefault();
var id = $(this).data('id');
$.ajax({
url: ajax_url,
type: 'POST',
data: {
action: 'load_post',
security: nonce,
id: id
},
success: function (data) {
if (data.success) {
var article = $(data.data.article);
$('.single-project').html(article);
$('html, body').animate({
scrollTop: ($("#single-project").first().offset().top)
}, 400);
} else {
console.log(data.data);
}
},
error: function (data) {
console.log('Error');
}
});
});
});
});
对于我的主 js 文件,我必须执行新的点击功能,如下所示:
$(document).on('click', '.nav-links a', function (event) {
event.preventDefault();
});
【问题讨论】: