对于与自定义分类术语链接的自定义帖子,使用get_posts()而不是query_posts() [英] get_posts() instead of query_posts() for a custom post linked with a custom taxonomy term
问题描述
我为模板构建了2个自定义帖子(消防员和马里奥),并且目前为他们每个构建了2个分类法(类型马里奥和术语游戏,类型消防员和术语游戏)
我使用query_posts()来显示与它们的术语链接的两个帖子的标题,但我想改用get_posts()。
I built 2 custom posts (firemen and mario) for my template, and I built for each of them 2 taxonomy (type-mario and the term game, type-firemen and the term game) at the moment I use query_posts() for showing title of both posts linked with their term but I d'like to use get_posts() instead.
<?php query_posts( array( 'type-mario' => 'games', 'showposts' => 10 ) ); ?>
<p>Mario games</p>
<?php while ( have_posts() ) : the_post(); ?>
<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<h2><?php the_title(); ?></h2>
</div>
<?php endwhile; ?>
<?php wp_reset_query(); ?>
<?php query_posts( array( 'type-firemen' => 'games', 'showposts' => 10 ) ); ?>
<p> Firemen Games </p>
<?php while ( have_posts() ) : the_post(); ?>
<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<h2><?php the_title(); ?></h2>
</div>
<?php endwhile; ?>
<?php wp_reset_query(); ?>
它很好用,但是我敢肯定,最好使用get_posts()来显示那两个标题帖子,但我不知道该怎么做。
It work well but I'm pretty sure that it's better to use get_posts() to show those 2 title posts, but I don't know how to do that.
PS:请记住,这里有2个海关帖子,而不是经典帖子,这是我不得不建立的原因我的每个具有相同术语的分类法...
PS: Remember that there are 2 customs posts and not classical posts, the cause of I had to build a taxonomy for each of my posts with the same term ...
感谢您的建议。
这里是一种解决方案:
<?php $posts = new WP_Query(array(
'taxonomy' => 'type-mario',
'term' => 'games',
'posts_per_page' => 10
)); ?>
<p>Mario games</p>
<?php while ( $posts->have_posts() ) : $posts->the_post(); ?>
<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<h2><?php the_title(); ?></h2>
</div>
<?php endwhile; ?>
<?php wp_reset_query(); ?>
推荐答案
如果您已经看过 get_posts()
它的功能类似于 query_posts()
。
两者之间的区别在于,使用 query_posts()
会修改全局变量,以便您使用
The difference between the two is that with query_posts()
it will modify globals so that you have the use of the "the_..." global functions.
使用 get_posts()
,它将返回一个发布对象数组您可以循环播放而不影响当前循环(如果有)。另外,您可以循环浏览多个帖子集。
With get_posts()
it will return an array of post objects which you can loop through without affecting the current Loop if any. Additionally you can loop through multiple post sets.
注意:在WordPress示例中, setup_postdata($ post)
函数,该函数将post对象添加为全局对象,这样您便可以使用 the _...全局函数(但是这样做会影响The Loop)。
Note: in the WordPress example, the setup_postdata($post)
function is used, which adds the post object as a global so that you are then able to use the "the_..." global functions (doing this however will affect The Loop).
注意: get_posts()
应该使用与 query_posts( )
。
这篇关于对于与自定义分类术语链接的自定义帖子,使用get_posts()而不是query_posts()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!