2
我創建了一個WordPress Widget,它可以獲取最近發佈的帖子,首先獲取具體的帖子數量, 然後有一個按鈕可以通過AJAX獲取更多帖子。窗口小部件類中的AJAX函數
完整的Widget代碼
/* 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();
}
}
這是AJAX代碼來獲得ajaxloadMore
功能輸出並追加到ul
標籤
$('#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
?
好,它的作品 使用query_posts,當我使用get_posts不起作用 –
什麼'WP_Query'?真的,不惜一切代價避免'query_posts'。 – brasofilo
如果您使用這個小部件兩次,如何得到這個值?例如在側邊欄和頁腳中。 – mattkrupnik