Wordpress:get&;商店类别信息


Wordpress: get & store category info

我想知道:有没有什么方法可以加载所有类别并将每个类别存储在不同的数组中?

所以我得到了这个代码:

<?php
$cat_args = array('orderby' => 'name','order' => 'ASC');
$categories = get_categories($cat_args);
foreach($categories as $category) {
    $args = array(
      'showposts'        => -1,
      'category__in'     => array($category->term_id),
      'caller_get_posts' => 1
    );
    $posts = get_posts($args);
    if ($posts) {
        echo '<p>Category: <a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a> </p> ';
        foreach($posts as $post) {
          setup_postdata($post);
          ?> <p><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></p> <?php
        } // foreach($posts
    } // if ($posts
} // foreach($categories
?>

我想制作它,这样我以后就可以这样使用它(在循环之外):

<?php echo $category[0] -> name . $category[1] -> name . $category[2] -> name; ?>

如果您只需要一个类别名称数组,您可以如下更改代码;(请注意:caller_get_postsshowposts几年前已经折旧。它们分别被ignore_sticky_postsposts_per_page取代

<?php
$cat_args = array('orderby' => 'name','order' => 'ASC');
$categories = get_categories($cat_args);
$category_names = array();
foreach($categories as $category) {
    $category_names[] = $category->name;
    $args = array(
      'posts_per_page'        => -1,
      'category__in'     => array($category->term_id),
      'ignore_sticky_posts' => 1
    );
    $posts = get_posts($args);
    if ($posts) {
        echo '<p>Category: <a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a> </p> ';
        foreach($posts as $post) {
          setup_postdata($post);
          ?> <p><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></p> <?php
        } // foreach($posts
    } // if ($posts
} // foreach($categories
?>

$category_names现在将保存一组类别名称。

如果你需要显示一个下面有帖子的类别列表,你应该在WPSE上查看我的帖子。您的方法非常耗费资源且速度缓慢。我的方法是超快速的,使用瞬态,并且在0.002秒内最佳情况下只进行2 db查询

注意:$categories变量中已经有了这种格式的数据。所以你可以在任何地方使用这种

<?php echo $categories[0] -> name . $categories[1] -> name . $categories[2] -> name; ?>