我有这段代码来显示当前帖子的作者的帖子,但我想做一个if语句,如果没有帖子,那么就回显一些文本。我现在有了这个,但它不起作用(上面是作者帖子的函数,下面是我的if语句):
<?php
function get_related_author_posts() {
global $authordata, $post;
$authors_posts = get_posts( array( \'author\' => $authordata->ID, \'post_type\' => \'kenniscentrum\', \'post__not_in\' => array( $post->ID ), \'posts_per_page\' => 5 ) );
$output = \'<ul>\';
foreach ( $authors_posts as $authors_post ) {
$output .= \'<li><a href="\' . get_permalink( $authors_post->ID ) . \'">\' . apply_filters( \'the_title\', $authors_post->post_title, $authors_post->ID ) . \'</a>\' . apply_filters( \'the_excerpt\', $authors_post->post_excerpt, $authors_post->ID ) . \'</li>\';
}
$output .= \'</ul>\';
return $output;
}
/*add this hook where you need the related posts*/
if(get_related_author_posts()) :
echo get_related_author_posts();
else :
echo \'No articles...\';
endif;
?>
有人能帮我解决这个问题吗?
最合适的回答,由SO网友:iEmanuele 整理而成
也许这样可以解决问题,将if语句放在函数中,检查检索到的帖子数是否大于等于1,如果是,则开始foreach else打印消息
function get_related_author_posts() {
global $authordata, $post;
$authors_posts = get_posts( array( \'author\' => $authordata->ID, \'post_type\' => \'kenniscentrum\', \'post__not_in\' => array( $post->ID ), \'posts_per_page\' => 5 ) );
if( $authors_posts && count( $authors_posts ) >= 1 ) :
$output = \'<ul>\';
foreach ( $authors_posts as $authors_post ) {
$output .= \'<li><a href="\' . get_permalink( $authors_post->ID ) . \'">\' . apply_filters( \'the_title\', $authors_post->post_title, $authors_post->ID ) . \'</a>\' . apply_filters( \'the_excerpt\', $authors_post->post_excerpt, $authors_post->ID ) . \'</li>\';
}
$output .= \'</ul>\';
else :
$output = \'<p>\'. __( \'No posts found\' ) .\'</p>\';
endif;
return $output;
}