我创建了一个 WordPress 小部件,它可以获取最近的帖子,首先获取特定数量的帖子,然后有一个按钮可以通过 AJAX 获取更多帖子。
完整的小部件代码
/* recent posts Widget
================================*/
class recent_posts extends WP_Widget {
public function __construct() {
// widget actual processes
parent::__construct(
'recent_posts', // Base ID
'recent posts', // Name
array( 'description' => __( 'Show the recent posts', 'foo'))
// Args
);
add_action('wp_ajax_ajaxloadMore', array($this,'ajaxloadMore'));
add_action('wp_ajax_nopriv_ajaxloadMore', array($this,'ajaxloadMore'));
}
// i remove form and update functions to reduce the code :)
public function widget( $args, $instance ) {
extract( $args );
$title = $instance['title'];
$number = $instance['num'];
// function for filter posts list where first post is the current post
if(is_single()){
function filter_where( $where = ''){
$where .= " AND post_date <= '" .get_the_date('Y-m-d H:i:s'). "'";
return $where;
}
add_filter( 'posts_where', 'filter_where' );
}
//select the current category ID
$category = get_the_category($post->ID);
$catid = $category[0]->cat_ID;
query_posts('cat='.$catid.'&showposts='.$number.'');
echo $before_widget;
echo $before_title .$title.$after_title;
echo '<ul class="recent_posts">';
while(have_posts()) : the_post();
echo '<li><a href="'.get_permalink().'">'.get_the_title().'</a></li><br>';
endwhile;
wp_reset_query();
echo '</ul>';
echo '<br><input type="button" id="loadMoreW" value="Load More" data-offset="'.$number.'">';
echo $after_widget;
}
// the ajax function
public function ajaxloadMore(){
// first need to get $catid and $number values from function widget
// second need to declare filter_where function to filter the query_posts here
query_posts('cat='.$catid.'&showposts='.$number.'&offset='.$_POST['offset'].'');
while(have_posts()) : the_post();
echo '<li><a href="'.get_permalink().'">'.get_the_title().'</a></li><br>';
endwhile;
wp_reset_query();
die();
}
}
这是获取ajaxloadMore
函数输出并附加到ul
标签的 AJAX 代码
$('#loadMoreW').on('click',function(){
$.ajax({
url: 'wp-admin/admin-ajax.php',
type: 'POST',
data: {
action : 'ajaxloadMore',
offset: $('#loadMoreW').data('offset')
},
success: function(data){
$('#loadMoreW').data('offset', $('#loadMoreW').data('offset')+4);
$(data).appendTo('.recent_posts');
}
});
});
如何从函数小部件中获取$catid
和$number
变量并将它们放入ajaxloadMore
函数中?
如何通过相同的功能过滤query_posts
功能ajaxloadMore
小部件的功能filter_where
?