【发布时间】:2012-03-10 06:52:37
【问题描述】:
我将帖子 ID 存储在一个数组中。我想遍历数组并在包含<p> 和<ul> 标签的<div> 中显示ID,但前提是数组中至少有一个ID。如果数组为空,则无法返回 html。这意味着我应该在循环之前使用某种 if 语句。不用说,我的 php 技能非常基础,经过两天的努力,我一无所获。感谢帮助!
我的代码(使用 Wordpress)
$postids = array();
...
$postids [] = $post->ID; //stores the post IDs in the array
这是一个更新。我很抱歉发布所有这些代码,因为它对很多事情都非常混乱。这是三个(或更多)的第二个循环。在几乎相同的第一个循环中显示的 ID 已被传递。仅显示上一个循环未检索到的那些 ID,以免显示任何重复的帖子。
我尝试删除所有 HTML 标记并在之后使用新的 WP_Query 查询 $postids,但这会检索我曾经创建的所有帖子。我很确定这是继续的正确方法,尽管我显然做错了。
<?php
$tags = wp_get_post_tags($post->ID);
if ($tags) {
$first_tag = $tags[1]->term_id;
$args=array(
'tag__in' => array($first_tag),
'post__not_in' => array($post->ID),
'showposts'=>5, //Display this number of related posts
'ignore_sticky_posts'=>1
);
$postids = array();
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
echo '<ul id="relatedposts">';
while ($my_query->have_posts()) : $my_query->the_post(); if (!in_array($post->ID, $ids)) {; $postids [] = $post->ID; ?>
<li><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
<?php }
$ids[]= $post->ID;
endwhile;
}
}
?>
</ul>
<?php if ($postids){ //$postids has at least one value set
echo '<div>Related posts</div>'; //Outputting the header text. This works! If there are no IDs in the array nothing is shown.
};
?>
【问题讨论】:
-
基本上我已经尝试弄清楚如何使用以下
<?php if (have_posts()) : ?> <div><p>header text</p> <?php while (have_posts()) : the_post(); ?> do stuff... <!--get the permalink, title etc...--> <?php endwhile; ?> </div> <?php endif; ?>循环数组但没有任何运气!
标签: php arrays loops if-statement while-loop