1

我正在使用此功能在 wordpress 中加载类别列表:

<?php wp_list_cats($args = array( 'current_category'   => 0, 'hide_empty'  => 1) );?>

谁能告诉我如何使类别链接链接到类别的第一篇文章?

IE:

目前类别 A 链接到 url.../category/category-a

我希望类别 A 链接到它的第一个帖子,而不是这样 url.../category-a/first-post

我尝试更改与以下内容一起使用的分类模板:

<?php
/*
Redirect To First Child
*/
if (have_posts()) {
 while (have_posts()) {
   the_post();
   $pagekids = get_pages("child_of=".$post->ID."&sort_column=menu_order");
   $firstchild = $pagekids[0];
   wp_redirect(get_permalink($firstchild->ID));
 }
}
?>

我只需要一个更简洁的解决方案,我不需要修改实际的 wordpress 文件。

谢谢

4

1 回答 1

1

我能想到的最好的,$posts数组现在包含每个类别中第一个帖子的链接。将此代码放在functions.php中:

function first_categories( $echo = false ) {
    $categories = get_categories();

    // array to hold links
    $posts = array();
    foreach ( $categories as $category ) {
        $post = get_posts( array( 'posts_per_page' => 1, 'post_type' => 'post', 'category' => $category->cat_ID ) );
        $posts[] = '<a href="'.get_permalink( $post[0]->ID ).'">'.$category->name.'</a>';
    }

    if ( $echo ) echo implode( '', $posts );
    else return $posts;
}

在模板文件中仅显示链接使用:

<?php first_categories( true ) ?>

或者,如果您想在 HTML 中包装链接,请使用以下内容:

<ul>
<?php foreach( first_categories() as $category ) : ?>
    <li><?php echo $category; ?></li>
<?php endforeach; ?>
</ul>

希望能帮助到你。

于 2013-05-11T20:27:26.010 回答