我正在使用WordPress作为我最喜欢的cms软件。使用过不同的WordPress特定查询,例如WP_Query
,get_posts
,query_posts
等。
我的问题是编程方面。如果我需要在特定的WordPress查询 - >循环中使用例如foreach
循环,该怎么办?我想,有时候在另一个wp循环中使用wp循环是不必要的,建议使用一个简单的php循环?
提前致谢!
答案 0 :(得分:3)
foreach
循环。
示例:的
$childrens = query_posts('showposts=10&&post_type=post');
foreach ( $childrens as $children ) {
// dos tuff here
}
要查看$children
中存储的数据,请使用print_r()
:
print_r( $childrens );
$children->ID
是对象属性的一个示例。
让我知道。
修改:有关foreach
的更多文档,此处:php-net foreach loops
答案 1 :(得分:1)
你可以在另一个循环中循环:
<?php while(have_posts()): the_post() ?>
<h2><?php the_title() ?></h2>
<?php
// preserve global post variable
global $post; $temp = $post;
$args = array('posts_per_page'=>3);
$args['tax_query'] = array(
array(
'taxonomy' => 'category',
'terms' => array('featured'),
'field' => 'slug',
)
);
$new_query = new WP_Query($args);
while($new_query->have_posts()): $new_query->the_post();
?>
<h3>Featured: <?php the_title() ?></h2>
<?php endwhile; $post = $temp; wp_reset_query(); ?>
<?php endwhile; ?>
上面的代码显示了“精选”类别中的3篇最新帖子。
答案 2 :(得分:1)
您
当前版本的WordPress(3.5及更低版本)并没有实现interators,但它提供了一些具有迭代器功能的方法。
例如foreach
have_posts()
将进入下一篇文章。但是在使用&#34; the loop&#34;中有效的函数之前,您仍然需要使用$query->
设置WP全局变量,因为这些函数依赖于全局变量
答案 3 :(得分:0)
虽然完全取决于你如何构建页面,但WordPress中The Loop
内部循环肯定有用例。
假设您有一个包含帖子列表的索引页面,并且在每个帖子下您要列出“相关帖子”。例如,您可以循环浏览帖子,然后使用WP_Query
foreach
通过具有相同标记的近期帖子。