Scenario:页面显示具有选定“类别”(在分类法中称为主题)的自定义帖子类型(视频)的标题列表。例如,主题为“创意”的视频
Problem如果存在符合条件的标题,则列表将正确显示,但如果没有标题,则页面上不会显示消息“未找到标题”。换句话说,echo语句失败了。
My Code
<?php $subject = $_GET[\'subject\'];
if ($subject=="") $subject = \'creativity\';?><?php /*If there is no value returned then the loop defaults to searching for items beginning with \'Creativity\' since its the first term.*/ ?>
<h2>Video Titles For <span class="colorBlack"><?php echo $subject ?></span></h2> <?php /*This needs to be outside of the loop*/?>
<?php
$loop = new WP_Query( array( \'post_type\' => \'video\', \'subject\' => $subject, \'posts_per_page\' => 10 ) ); ?>
<?php if (have_posts() ):?>
<?php while ( $loop->have_posts() ) : $loop->the_post();?>
<div class="glossarybody">
<h2><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></h2>
</div>
<?php endwhile;
else: echo \'No Titles Found\';
endif;
?>
查看法典,“if-else”的形式如下所示:
<?php
if ( have_posts() ) :
while ( have_posts() ) : the_post();
// Your loop code
endwhile;
else :
echo wpautop( \'Sorry, no posts were found\' );
endif;
?>
因此,我似乎有正确的语法,由于“if”部分功能正确,我假设它有正确的语法。
如果有人能告诉我哪里出了问题,我将不胜感激。
谢谢
SO网友:Steven
为什么使用WP_Query
? 我想你可以用get_posts
.
我没有使用列表中没有的参数进行测试,但应该可以。
这就是我要做的。
$args=array(
\'subject\' => $subject,
\'post_type\' => \'video\',
\'post_status\' => \'publish\',
\'posts_per_page\' => 10
);
$videos = get_posts( $args );
$has_video = true;
// Loop through the posts
foreach ($videos as $video) : setup_postdata($video); ?>
// We assume that all posts have a title.
if(!empty(get_the_title()) {
<div class="glossarybody">
<?php the_title(); ?>
<?php the_excerpt(); ?>
</div>
} else {
$has_video = false;
}
endforeach;
if(!$has_video)
_e(\'Sorry, no posts were found\');