【问题标题】:Wordpress show posts within a table, else echo <div>Wordpress 在表格中显示帖子,否则回显 <div>
【发布时间】:2018-01-30 06:13:37
【问题描述】:

在表格中显示来自我的custom_post_type 的帖子时遇到问题。

目前正在使用

<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>

当帖子存在时,这会为每个帖子正确显示the_title。但是,当没有帖子存在时,它不会显示else : echo

这张图片显示了处理帖子的表格,我从上面的代码中删除了列以简化所询问的内容

没有帖子 - 没有消息

感谢您的宝贵时间!

【问题讨论】:

  • 为什么要这样做?将表格用于除表格数据之外的任何内容通常都是不好的做法。
  • 谢谢你,Nathaniel,我在上面添加了一些截图来展示。你能建议另一种方法吗?该页面显示每个订阅者构建的活动的帖子。在这里,他们可以编辑、查看或查看他们拥有的每个广告系列的报告。干杯。
  • 啊,你在使用表格数据。
  • 是的,为了让问题简单,我刚刚删除了大多数。我已经阅读了很多你对其他问题的回答,随着时间的推移,它们对查询有所帮助。感谢您抽出宝贵时间回答我的问题。
  • 太棒了,感谢您的反馈!

标签: php wordpress loops custom-post-type


【解决方案1】:

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

只需更换

if (have_posts()) :

if ($query->have_posts()) :

更多信息click here

额外建议

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

【讨论】:

  • @DarrenMathers 还添加了 wp_reset_postdata();在while循环之后
  • 谢谢你,Ankur。确实如此。
猜你喜欢
  • 1970-01-01
  • 2019-07-18
  • 1970-01-01
  • 2017-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多