获取查询中的类别名称

时间:2013-12-14 作者:user43862

我有父类别、游戏(cat ID 42)和一些子类别:Acrade、Causaul。在我使用循环获取文章标题之后,我希望有一个子类别名称。但我的代码不起作用:

<?php 
$args = array(
    \'cat\'            => 42,
    \'posts_per_page\' => 12,
    \'post__in\'       => get_option( \'sticky_posts\' ),
);

// The Query
$the_query = new WP_Query( $args );
$categories = get_the_category($post->ID);

// The Loop
while ( $the_query->have_posts() ) : 
    $the_query->the_post();
?>

<?php
/* if post has a thumbnail */
if (  ( function_exists(\'has_post_thumbnail\') ) && ( has_post_thumbnail() )  ) { ?>

<li>
  <a href="<?php the_permalink(); ?>" rel="bookmark" title="Permanent Link: <?php the_title(); ?>"><?php the_post_thumbnail(\'app_icon\', array(\'title\' => get_the_title())); ?></a>
  <p class="ptit">
    <a href="<?php echo get_permalink() ?>" rel="bookmark" title="Permanent Link: <?php the_title(); ?>"><?php the_title(); ?></a>
  </p>
  <span class="cate"><?php echo $categories ?></span>
</li>

<?php
} /* end if post has a thumbnail */

endwhile;

// Reset Post Data
wp_reset_postdata();
?>

2 个回复
最合适的回答,由SO网友:gmazzap 整理而成

当你打电话的时候

$categories = get_the_category($post->ID);
the$post 变量尚未定义(或不是您期望的变量),因为您必须使用它inside 循环。

你在哪里

<span class="cate"><?php echo $categories ?></span>
替换为(这将输出类似“Game,Arcade”的内容)

<span class="cate"><?php the_category(\', \'); ?></span>
或者如果要删除父cat

<span class="cate">
<?php
$categories = get_the_category();
if( $categories ){
  $o = \'\';
  $sep = \', \';
  foreach($categories as $c) {
    if ( $c->parent == 0 ) continue;
    $o .= $c->cat_name . $sep;
  }
  echo rtrim($o, $sep);
}
?>
</span>

SO网友:user43862

在主页上有工作。但在navsidebar中,代码不起作用。标题中的我的代码。php。我想问,如何只获取第一个项目的缩略图,与1移动页面相同enter image description here

<div class="mb10">
         <div class="sidetoplist">
             <div class="title"><h3 class="tit">Latest Games</h3></div>
             <div class="first"><a href="/subway-surfers-574540.html" class="pic"><img src="http://img.1mobile.com/market/iconv2/36/36542a7ff008ac4ab8440c34b8f02f40-s144.png" alt="Subway Surfers"></a></div>
             <ul class="list clearfix" id="topgames">
                                    <?php  
$args=数组(\'cat\'=>42,\'posts\\u per\\u page\'=>10,\'orderby\'=>\'date\');//查询$count=1$\\u query=新的WP\\u查询($args);

//Loopwhile($The\\u query->have\\u posts()):$The\\u query->The\\u post();?>

                        <li><em class="num"><?php echo $count?>.</em><a href="<?php echo get_permalink() ?>" rel="bookmark" title="Permanent Link: <?php the_title(); ?>"><b><?php the_title(); ?></b><i><?php
$类别=获取\\u类别();if($categories){$o=“”;$sep=\',\';foreach($c作为$c的类别){if($c->parent==0)continue;$o=$c->cat\\u name。$sep;}echo rtrim($o,$sep);}?>

                        <?php }
                        $count++;
                    endwhile;
//Reset Post Datawp\\u Reset\\u postdata();?>

             </ul>
         </div>

结束