2012-07-14 85 views
1

我试图让我最近发表的文章列表中也可看出他们是什么类别的,现在我有WordPress的获取最近的职位和显示名称和类别名称

<?php $args = array( 'numberposts' => 30) ; 
$recent_posts = wp_get_recent_posts($args); 
foreach($recent_posts as $recent){ 
echo '<li> 
    <a href="'.get_permalink($recent["ID"]).'" title="Look'.esc_attr($recent["post_title"]).'" > '.$recent["post_title"].'</a> </li> '; } ?> 

这显示了职位,但我希望它也显示类别名称。

任何帮助将是巨大的,

感谢

+0

我尝试添加一个变量$猫但是当它显示页面它打印出阵列<?PHP的\t的$ args =阵列( 'numberposts'=> 10); $ cats = get_the_category(); \t $ recent_posts = wp_get_recent_posts($ args); \t的foreach($ recent_posts为$近期){ \t回声 '

  • '.$recent["post_title"].''。$猫。”
  • '; \t}?> – 2012-07-15 03:14:20

    回答

    2
    $cats = get_the_category($recent["ID"]); 
    $cat_name = $cats[0]->name; // for the first category 
    

    你可以试试这个循环里面(如果你有多个类别)

    $cats = get_the_category($recent["ID"]); 
    foreach($cats as $cat) 
    { 
        echo $cat->name." "; 
    } 
    
    +0

    你能解释一下吗?我对PHP和wordpress很陌生。 – 2012-07-15 03:12:04

    +1

    '$ cats = get_the_category($ recent [“ID”]);'将在'foreach'循环中检索与当前帖子相关的所有类别,并且该函数接受一个参数(可选)来确定帖子,然后返回一个对象数组,并使用另一个“foreach”循环,我们用它们之间的“空格”回显所有类别。 [参考这里](http://codex.wordpress.org/Function_Reference/get_the_category)。 – 2012-07-15 07:23:29

    0

    我能得到一个列表通过使用以下内容显示类别,然后显示标题。

    <?php 
        $recentPosts = new WP_Query(); 
        $recentPosts->query('showposts=30');?> 
    <?php while ($recentPosts->have_posts()) : $recentPosts->the_post(); ?> 
    <?php the_category(" "); ?>-<a href="<?php the_permalink()?>"> <?php the_title(); ?></a> 
    <?php endwhile; ?><?php wp_reset_query()?> 
    

    我从来没有能够得到下面的代码我原来代码中的工作,它会一直显示为“阵列”或空(我猜我只是不知道把它写在适当的方式)如果我创建了一个帖子,并且只想显示其他类别,我就能够显示该类别。

    $cats = get_the_category($recent["ID"]); 
    foreach($cats as $cat){ 
    echo $cat->name." "; } 
    
    1

    我能够得到这个使用以下工作。

    $cats[0]->name." " 
    

    所以在最近的帖子循环中,您可以使用它像这样:

    $args = array('numberposts' => 5, 'category' => '4,5'); 
    $recent_posts = wp_get_recent_posts($args);  
    
    foreach($recent_posts as $recent){ 
        $cats = get_the_category($recent["ID"]); 
        echo '<li><a href="' . get_permalink($recent["ID"]) . '" title="Look '.esc_attr($recent["post_title"]).'">' . $cats[0]->name." " . $recent["post_title"].'</a> </li> '; 
    } 
    
    0

    我使用雅科答案,但

    $cats[0]->name 
    

    给我从数组中第一类在每个帖子上。我做的调整是在代码中使用增量运算符,一切都很好。

    一个更简化的例子:

    ​​
    相关问题