其他代码片段的主要问题是get_the_cagetory()
函数外循环,是的,你可以这样使用它,但是通过$post->ID
参数明智的做法是将代码片段放在循环中,避免不必要的全局调用。
在这之后,特雷弗的循环是这样的:
<!-- The Loop -->
<?php if( have_posts() ): while(have_posts()): the_post(); ?>
<div <?php post_class(); ?> id="post-<?php the_ID(); ?>">
<div class="date"><div class="date_content"><?php the_time(\'dS\'); ?> <?php the_time(\'M\'); ?><span><?php the_time(\'Y\'); ?></span></div></div>
<div class="post_content">
<?php $category = get_the_category();
$first_cat = ( !empty( $category[0] ) ) ? $category[0]->cat_name : \'\'; ?>
<h2 class="postitle"><a href="<?php the_permalink();?>"><?php the_title( "$first_cat: " ); ?></a></h2>
<div class="single_metainfo">by <?php the_author(); ?></div>
<?php the_content(); ?>
<?php wp_link_pages(\'<p class="pages"><strong>\'.__(\'Pages:\').\'</strong> \', \'</p>\', \'number\'); ?>
</div>
注意后面的行
<div class="post_content">
.
我的第二个解决方案是使用the_title
滤器
function mamaduka_category_perefix_title( $title, $id ) {
$category = get_the_category( $id );
if ( ! empty( $category[0] ) )
$title = sprintf( \'%1$s: %2$s\', $category[0]->cat_name, $title );
return $title;
}
add_filter( \'the_title\', \'mamaduka_category_perefix_title\', 10, 2 );
But this code has side effect. It will prefix every title inside the loop, including widgets like "Recent Posts".