问题描述
我有一个 sidebar.php
最新帖子的列表。以下是代码的示例:
<?php $args = array('posts_per_page' => 20); ?>
<?php $sidebar = new WP_Query($args); ?>
<?php if ( $sidebar->have_posts() ) : ?>
<?php while ( $sidebar->have_posts() ) : $sidebar->the_post(); ?>
<div class="story">
<a href="<?php%20the_permalink();%20?>" title="<?php the_title(); ?>">
<?php the_title(); ?> - <?php the_time("F j, Y h:i A"); ?>
</a>
</div>
<?php endwhile; ?>
<?php endif; ?>
那部分功能完美。它显示 20 个最新的帖子标题和邮政时间包裹在永久链接。但是,我正在努力做一点。我想在底部创建一个加载更多按钮,以获取接下来的 20 个帖子标题。我知道我的 jQuery,这不是问题。
我需要帮助,找出如何在仅仅生成上面的 html 的新的自定义.php
模板文件中创建自定义循环。该文件需要能够接受一个页码的参数,这样我的 javascript
可以每次获取递增的 URL 。
谢谢任何帮助,谢谢!
最佳解决方案
你可以包装你的函数并挂钩到 ajax 调用,如下所示:
//if you want only logged in users to access this function use this hook
add_action('wp_ajax_more_links', 'my_AJAX_more_links_function');
//if you want none logged in users to access this function use this hook
add_action('wp_ajax_nopriv_more_links', 'my_AJAX_more_links_function');
function my_AJAX_more_links_function(){
check_ajax_referer('more_links');
$success_response = new WP_Ajax_Response();
$args = array('posts_per_page' => 20 , 'offset' => $_POST['offset']);
$sidebar = new WP_Query($args);
if ( $sidebar->have_posts() ){
while ( $sidebar->have_posts() ) {
$sidebar->the_post();
$out .= '<div class="story">';
$out .= '<a href="'%20.%20the_permalink().'" title="'. the_title'.">' . the_title().' - '.the_time("F j, Y h:i A") .'</a></div>';
}
$success_response->add(array(
'what' => 'has',
'data' => array('html' => $out, 'offset' => $_POST['offset']
));
}else{
$out = __('Sorry but No more!');
$success_response->add(array(
'what' => 'none',
'data' => $out
));
}
$success_response->send();
exit;
}
然后将其添加到您的侧栏功能结束
<span class="more_links"></span>
<span class="get_more">
<input type="hidden" name="offset" id="offset" value="20">
<input type="submit" name="more" id="more" value="Get more links">
</span>
<script type="text/javascript" >
jQuery(document).ready(function($) {
jQuery('#more').click(function() {
var data = {
action: 'more_links',
offset: jQuery( '#offset' ).val(),
_ajax_nonce: <?php echo wp_create_nonce( 'more_links' ); ?>
};
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
jQuery.post(ajaxurl, data, function(response) {
var res = wpAjax.parseAjaxResponse(response, 'ajax-response');
jQuery.each( res.responses, function() {
if (this.what == 'has') {
//insert links
jQuery(".more_links").append( this.data.html );
//update offset value
jQuery("#offset").val(this.data.offset);
jQuery(".more_links").fadeIn("fast");
}else{
//no more links found
jQuery(".more_links").append( this.data.html );
jQuery(".get_more").remove();
}
//end if
});//end each
});
return false;
})
});
</script>
那你去,哦,等你需要添加 wp-ajax-response
add_action('wp_head','add_scripts_121');
function add_scripts_121(){
wp_enqueue_script('wp-ajax-response');
}
你设置好了
参考文献
注:本文内容整合自 Google/Baidu/Bing 辅助翻译的英文资料结果。如果您对结果不满意,可以加入我们改善翻译效果:薇晓朵技术论坛。