Wordpress 在 table 内显示帖子,否则回显 <div>

Wordpress show posts within a table, else echo <div>

在 table 中显示来自我的 custom_post_type 的 post 时遇到问题。

目前正在使用

<table>
<thead>
    <tr>
        <th>Title</th>
    </tr>
</thead>
<tbody>
<?php $query = new WP_Query( array( 'post_type' => 'custom_post_type' ) );?>
<?php if (have_posts()) : while ( $query->have_posts() ) : $query->the_post(); ?>
    <tr>
        <td>
        <?php the_title(); ?>
        </td>
    </tr>
<?php endwhile; ?>
<?php else: echo "<tr>" . __( "Sorry, there are no posts." ) . "</tr>";endif; ?>
</tbody>

当 post 存在时,这会正确显示每个 post 的 the_title。但是,当不存在 post 时,它不会显示 else : echo

此图显示了 table 使用 posts,我从上面的代码中删除了列以简化所询问的内容

并且没有 posts - 没有消息

感谢您的宝贵时间!

对于自定义查询,您需要使用 Wp_Query 对象来检查 have_posts()

只需替换

if (have_posts()) :

if ($query->have_posts()) :

更多信息click here

Extra suggestion

while循环后添加wp_reset_postdata();恢复全局$post变量