我已经构建了自己的自定义“最近的帖子”小部件,以显示比默认的核心WP最近的帖子小部件更多的内容。我正在努力控制我的条目列表。当前,小部件总是向所选列表返回一条额外的帖子。因此,如果我选择1篇文章来显示,它实际上会显示2篇,以此类推。我真的不确定我的代码哪里出错了:
// Run query to build posts listing
public function getPostsListings($numberOfListings,$showExcerpt,$showDate,$showFeatImage,$post_excerpt_length)
{
$post_listings = new WP_Query();
$post_listings->query(\'posts_per_page=\' . $numberOfListings, \'ignore_sticky_posts\' => 1);
if ($post_listings->found_posts > 0) {
echo \'<ul class="posts_widget">\';
while ($post_listings->have_posts()) {
$post_listings->the_post();
$listItem = \'<li>\';
if ( !empty($showFeatImage) && has_post_thumbnail() ) {
$listItem .= \'<img src="\'. get_the_post_thumbnail_url(get_the_ID(),\'thumbnail\') .\'" />\';
}
$listItem .= \'<a href="\' . get_permalink() . \'">\';
$listItem .= get_the_title() . \'</a>\';
if (!empty($showDate)) {
$listItem .= \'<span class="post-date"> Posted: \' . get_the_date() . \'</span>\';
}
if (!empty($showExcerpt)) {
$listItem .= \'<span class="post-excerpt">\' .wp_trim_words( get_the_excerpt(), $post_excerpt_length). \'</span>\';
}
$listItem .= \'</li>\';
echo $listItem;
}
echo \'</ul>\';
wp_reset_postdata();
} else {
echo \'<p>No posts were found</p>\';
}
}
很明显,这个小部件的代码比这个多,但为了简洁起见,我保留了它,因为我相当确定我的while循环是核心问题。
SO网友:Ryan Coolwebs
正如@jacob和@Sneha之前在评论中提到的那样,我的问题是粘性帖子不计入“每页posts\\u”。我的更新代码如下:
// Run query to build posts listing
public function getPostsListings($numberOfListings,$showExcerpt,$showDate,$showFeatImage,$post_excerpt_length)
{
global $post;
$args = array( \'numberposts\' => $numberOfListings, \'ignore_sticky_posts\' => 1);
$recent_posts = get_posts( $args );
if ( have_posts() ) {
echo \'<ul class="posts_widget">\';
foreach( $recent_posts as $post ) : setup_postdata($post);
setup_postdata($post);
$listItem = \'<li>\';
if ( !empty($showFeatImage) && has_post_thumbnail() ) {
$listItem .= \'<img src="\'. get_the_post_thumbnail_url(get_the_ID(),\'thumbnail\') .\'" />\';
}
$listItem .= \'<a href="\' . get_permalink() . \'">\';
$listItem .= get_the_title() . \'</a>\';
if (!empty($showDate)) {
$listItem .= \'<span class="post-date"> Posted: \' . get_the_date() . \'</span>\';
}
if (!empty($showExcerpt)) {
$listItem .= \'<span class="post-excerpt">\' .wp_trim_words( get_the_excerpt(), $post_excerpt_length). \'</span>\';
}
$listItem .= \'</li>\';
echo $listItem;
endforeach;
echo \'</ul>\';
wp_reset_postdata();
} else {
echo \'<p>No posts were found</p>\';
}
}
我确实通过重新分配此处的代码示例,以另一种替代方式解决了此问题:
https://themefuse.com/how-to-create-a-recent-posts-wordpress-plugin/