【问题标题】:How can I exclude only latest post in certain category from showing in loop?如何仅排除特定类别中的最新帖子而不显示在循环中?
【发布时间】:2015-11-18 14:23:28
【问题描述】:

我有两个循环和查询。

在页面顶部我有这段代码。它只显示名为“精选”类别的最新帖子:

<?php
    $latest_featured_post = new WP_Query ( array ( 'category_name' => 'featured', 'posts_per_page' => 1 ) );
    while ($latest_featured_post->have_posts()) : $latest_featured_post->the_post();
?>

现在我想从同一页面上的另一个主循环中排除该帖子,因为我不希望它显示两次。我试图通过在“特色”类别中捕获最新帖子的 ID 并将其传递给“post__not_in”参数来实现这一点,但我做错了。这是我的代码

<?php 

        $category_id = get_cat_ID('Događaji');
        $exlude_latest_featured_post = array($latest_featured_post->ID);
        $args = array(
            'category__not_in' => array($category_id),
            'post__not_in' => $exlude_latest_featured_post,
        );

        query_posts( $args );
        while (have_posts()) : the_post(); ?>

    <?php get_template_part('loop/content'); ?> 

我尝试手动传递帖子的 ID(例如,'post__not_in' => array(1337))并且它有效。这意味着我在捕捉“精选”最新帖子 ID 时犯了错误。

我在 Google 上搜索答案,但没有找到任何有用的信息。希望这里有人有时间和正确的答案

谢谢

【问题讨论】:

  • 只是一个注释,从来没有使用query_posts,它破坏了破坏页面功能的主要查询对象。
  • 感谢彼得的建议。我将所有 query_posts 更改为 WP_Query

标签: php wordpress loops


【解决方案1】:

您可以通过get_the_id 函数在第一个循环中捕获精选帖子ID,然后在后面的循环中使用它:

<?php
    $latest_featured_post = new WP_Query ( array ( 'category_name' => 'featured', 'posts_per_page' => 1 ) );
    while ($latest_featured_post->have_posts()) : 
        $latest_featured_post->the_post(); 
        $featuredID = get_the_id();
?>

你的后一个循环:

    $category_id = get_cat_ID('Događaji');
    $exlude_latest_featured_post = array($featuredID);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-01
    • 1970-01-01
    • 2010-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多