【问题标题】:How to display featured posts outside of the loop on a category page, where posts must match the category如何在类别页面上的循环之外显示精选帖子,其中帖子必须与类别匹配
【发布时间】:2021-06-03 11:41:11
【问题描述】:

我正在尝试在所有类别页面上,在显示帖子的循环上方建立一个“热门文章”区域。我在每个帖子上添加了一个“精选帖子”复选框,允许管理员将某些帖子标记为精选帖子,并且我已经能够在每个类别页面的顶部显示这些帖子。但它目前在所有类别页面上显示所有精选帖子,我需要系统过滤帖子以显示仅显示与它们显示的页面属于同一类别的帖子。

这是我在我的函数文件中使用的,它可以很好地显示特色帖子 - 感谢任何添加类别过滤的帮助!

  $args = array(
        'posts_per_page' => 5,
        'meta_key' => 'meta-checkbox',
        'meta_value' => 'yes'
    );
    $featured = new WP_Query($args);
 
if ($featured->have_posts()): while($featured->have_posts()): $featured->the_post(); ?>
<h3><a href="<?php the_permalink(); ?>"> <?php the_title(); ?></a></h3>
<p class="details">By <a href="<?php the_author_posts() ?>"><?php the_author(); ?> </a> / On <?php echo get_the_date('F j, Y'); ?> / In <?php the_category(', '); ?></p>
<?php if (has_post_thumbnail()) : ?>
 
<figure> <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail(); ?></a> </figure>
<p ><?php the_excerpt();?></p>
<?php
endif;
endwhile; else:
endif;
?>```

【问题讨论】:

    标签: wordpress categories posts


    【解决方案1】:

    如果您只需要 category 存档页面而不需要其他或自定义分类法,那么您只需要全局变量 $category_name。尽管它被称为“名称”,但它实际上是类别 slug,它允许我们在将附加到查询的 tax_query 字段中使用它。

    首先,我们使$category_name 可用,然后在我们的查询中使用它以及您的元字段:

    global $category_name;
    
    $featured_posts = new WP_Query(
        [
            "showposts"  => 5,
            "meta_key"   => "meta-checkbox",
            "meta_value" => "yes",
            "tax_query"  => [
                [
                    "taxonomy" => "category",
                    "field"    => "slug",
                    "terms"    => $category_name,
                ],
            ]
        ]
    );
    

    这将为我们提供以下帖子

    • 在当前分类存档页面的分类内,
    • 由管理员通过meta-checkbox 元键标记为精选帖子

    现在我们可以使用这些帖子并循环浏览它们。这是一个非常简单的循环,几乎没有标记:

    if ($featured_posts->have_posts()) {
        while ($featured_posts->have_posts()) {
            $featured_posts->the_post();
            ?>
             <h3>
                 The post "<?php the_title(); ?>" is in category "<?php the_category(" "); ?>"
             </h3>
            <?php
        }
    }
    else {
        ?>
        <h3>No featured posts were found :(</h3>
        <?php
    }
    

    这是一个外观示例。如您所见,所有五个帖子都与存档页面类别属于同一类别。

    我希望这会有所帮助。

    【讨论】:

    • 非常感谢!非常感谢您花时间帮助一个陌生人,这正是我想要的!
    猜你喜欢
    • 1970-01-01
    • 2011-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多