如何在WordPress主题中仅显示具有某些类别的帖子?

发布于 2025-01-17 23:56:17 字数 371 浏览 3 评论 0原文

我想知道是否有一种方法可以更改此代码以仅显示在 WordPress 中创建的特定类别的帖子。现在它显示每一个最近的帖子。假设我要在 WordPress 中创建“新闻”类别,并且我希望这段代码仅显示新闻帖子。

感谢您的帮助

<?php
        if( have_posts() ){

            while( have_posts() ){

                the_post();
                get_template_part( 'template-parts/content', 'koncert');
                
            }
        }
?>

I was wondering if there is a way to change this code to only display posts from certain category created in wordpress. Now it displays every recent post. Let's say I would create "News" category in wordpress and I want this piece of code to display only News posts.

Thanks for help

<?php
        if( have_posts() ){

            while( have_posts() ){

                the_post();
                get_template_part( 'template-parts/content', 'koncert');
                
            }
        }
?>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

蓝色星空 2025-01-24 23:56:17

您可以覆盖 WordPress 使用的常用查询并创建自定义查询;

https://developer.wordpress.org/reference/classes/wp_query/

通常不过,如果仅显示类别,您只需打开类别标签,只要您的模板具有正确的存档页面,它将显示该类别的帖子。

如果没有使用类似于下面的东西。您可以进一步细化搜索参数,例如上面链接中定义的帖子数量和帖子类型。

    <?php
    
      //refine your query to the category you desire either a slug(example below) or category id
      $args = array(
        'category_name' => 'my_category_slug', 
      );
    
      //create the query using the arguments
      $query = new WP_Query($args);
    
    ?>
    
    //create the loop to show the posts
    <?php if($query->have_posts()): ?>
    
     <?php while($query->have_posts()): $query->the_post(); ?>
    
      <h1><?php the_title(); ?></h1>
    
      <div><?php the_content(); ?></div>
    
     <?php endwhile; ?>
    
    <?php endif; ?>

You can override the usual query that wordpress uses and create a custom one;

https://developer.wordpress.org/reference/classes/wp_query/

usually though for just displaying a category you can just open the category slug and provided your template has the correct archive page it will display the posts for that category.

If not use something similar to below. You can further refine your search parameters like number of posts and post types as defined in the link above.

    <?php
    
      //refine your query to the category you desire either a slug(example below) or category id
      $args = array(
        'category_name' => 'my_category_slug', 
      );
    
      //create the query using the arguments
      $query = new WP_Query($args);
    
    ?>
    
    //create the loop to show the posts
    <?php if($query->have_posts()): ?>
    
     <?php while($query->have_posts()): $query->the_post(); ?>
    
      <h1><?php the_title(); ?></h1>
    
      <div><?php the_content(); ?></div>
    
     <?php endwhile; ?>
    
    <?php endif; ?>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文