如何使用slug从类别中获取帖子?

时间:2012-11-02 20:01:34

标签: wordpress

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

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

<?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获得该类别怎么办?或者是否可以在管理面板中简单地创建一个类别选择框?

3 个答案:

答案 0 :(得分:26)

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

答案 1 :(得分: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(); ?>

答案 2 :(得分:0)

您只需在WordPress的get_posts方法中传递子弹 假设您的类别标签是ice-cake

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

有关更多信息:https://developer.wordpress.org/reference/functions/get_posts/

相关问题