仅从最新帖子提要 wordpress 中排除一个类别的第一篇文章


Exclude only first post from one category from the latest posts feed, wordpress

我管理一个运行Wordpress的网站(www.teknologia.no)。正如您在首页上看到的,我在页面顶部有一篇"主要/精选"文章,显示了特定类别的最新帖子。在它下面,我有一个主循环,显示所有类别的所有最新帖子。

但正如您从标题中看到和阅读的那样,当帖子被选为顶部特色空间中的位置时,它也会显示在最新的帖子提要中。

我的问题正如我的标题所说:我怎样才能排除某个类别中的最新/最新帖子与所有最新帖子一起出现。

我知道我可以通过在一段时间后更改类别等来手动控制它,但我希望它自动完成,我不知道如何完成。

希望你能抽出一些时间,帮我:)

您需要更新模板的逻辑,以便主循环跳过输出顶部输出的帖子。

如果没有看到您的模板代码,很难具体,但这样的事情可能会起作用:

在顶部,保存要输出的帖子的 ID:

$exclude_post_id = get_the_ID();

如果您需要直接获取给定类别中最新帖子的 ID,而不是在循环期间保存它,您可以使用WP_Query来执行此操作:

$my_query = new WP_Query('category_name=my_category_name&showposts=1');
while ($my_query->have_posts()):
    $my_query->next_post();
    $exclude_post_id = $my_query->post->ID;
endwhile;

然后,在主循环中,更改查询以排除该帖子:

query_posts(array('post__not_in'=>$exclude_post_id));

或者在循环中手动排除它,如下所示:

if (have_posts()): 
    while (have_posts()):
        the_post();
        if ($post->ID == $exclude_post_id) continue;
        the_content();
    endwhile;
 endif;

更多信息在这里,这里和这里。

这里有一个函数可以做到这一点:

function get_lastest_post_of_category($cat){
$args = array( 'posts_per_page' => 1, 'order'=> 'DESC', 'orderby' => 'date', 'category__in' => (array)$cat);
$post_is = get_posts( $args );
return $post_is[0]->ID;

}

用法:假设我的类别ID是22,然后:

$last_post_ID = get_lastest_post_of_category(22);

您还可以将类别数组传递给此函数。

启动一个变量并检查循环内部。一个简单的方法:

$i=0;
while(have_posts() == true)
{
 ++$i;
 if($i==1) //first post
  continue;
 // Rest of the code
}
您可以使用

query_posts('offset=1');

获取更多信息 : 博客

方法 - 1

$cat_posts = new WP_Query('posts_per_page=1&cat=2'); //first 1 posts
while($cat_posts->have_posts()) { 
   $cat_posts->the_post(); 
   $do_not_duplicate[] = $post->ID;
}
//Then check this if exist in an array before display the posts as following.
 if (have_posts()) {
    while (have_posts()) {
    if (in_array($post->ID, $do_not_duplicate)) continue; // check if exist first post
     the_post_thumbnail('medium-thumb'); 
         the_title();
    } // end while
}

方法 - 2

query_posts('posts_per_page=6&offset=1');
if ( have_posts() ) : while ( have_posts() ) : the_post();

此查询告诉循环仅显示最近第一篇文章之后的 5 个帖子。这段代码中的重要部分是"偏移",这个神奇的词正在做整个事情。

更多细节从这里

从最近的五个帖子中排除第一个

<?php 
   // the query
   $the_query = new WP_Query( array(
     'category_name' => 'Past_Category_Name',
      'posts_per_page' => 5,
              'offset' => 1
   )); 
?>