12

我有自己的主题,我想在我的主页上显示特定类别的帖子。

到目前为止,我已经实现了这样的目标:

<?php
    global $post;
    $args = array( 'numberposts' => 10, 'category' => 6 );
    $posts = get_posts( $args );
    foreach( $posts as $post ): setup_postdata($post); 
?>

    <divs with the_title() the_excerpt() etc ></div>

<?php 
    endforeach; 
?>

但是,如果我想通过它的 slug 来获取类别呢?或者是否可以从管理面板中简单地制作一个类别选择框?

4

3 回答 3

43

将您的category参数替换为category_name

<?php
    global $post;
    $args = array( 'numberposts' => 10, 'category_name' => 'cat-slug' );
    $posts = get_posts( $args );
    foreach( $posts as $post ): setup_postdata($post); 
?>

<divs with the_title() the_excerpt() etc ></div>

<?php endforeach; ?>

欲了解更多信息:http ://codex.wordpress.org/Class_Reference/WP_Query#Parameters

于 2012-11-03T08:32:50.280 回答
4

假设您有类别名称“冰蛋糕”和类别 slug 为“冰蛋糕”,那么我们检索“冰蛋糕”类别下的帖子的代码如下:

<?php
              $args = array( 'posts_per_page' => 3,
               'category_name' => 'ice-cakes' );

              $icecakes = get_posts( $args );
              foreach ( $icecakes as $post ) : setup_postdata( $post ); ?>
                  <li>
                      <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
                  </li>
              <?php endforeach; 
              wp_reset_postdata(); ?>
于 2018-01-05T09:51:22.227 回答
0

假设您的类别slugget_postsice-cake

$args = array('numberposts' => 10, 'category' => 'ice-cake');
$posts = get_posts($args);

欲了解更多信息:https ://developer.wordpress.org/reference/functions/get_posts/

于 2019-09-21T08:28:35.170 回答