我已经注册了一个定制的post类型,并输入了我的归档-myCPT.php,我想检索,,当前发布的文章。下面是我的存档-myCPT.php中的相关片段:
if( have_posts() ){
$x = 1;
while ( have_posts() ){
the_post();
if ( 0 === (int) $post->post_parent) {
get_template_part( 'inc/post-format/content-debate');
}我如何在这个循环中添加一个条件来检查当前发布的帖子并只检索一个(最近的)?这有可能吗?如果是的话,我怎样才能做到呢?
发布于 2013-11-23 14:05:18
我们可以直接检索post,过滤wp_query参数中的选择
<?php
// The Query
$args=array(
'post_type'=>'custom-post-type',
'posts_per_page'=>1,
'post_parent'=>'parent-page-id',
'order'=>'DESC'
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();?>
/*title*/ <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
/*image*/ <?php the_post_thumbnail(); ?>
<?php }}
wp_reset_postdata();?>因此,不需要在循环中进行过滤。希望这能有所帮助。
发布于 2013-11-22 16:04:45
在循环中,您只得到已发布的帖子,因此这不是您所关心的问题。
如果您希望得到最后一篇发表的文章,请在if(have_posts())函数query_posts('posts_per_page=1&order=DESC&orderby=date&post_type=my_custom_post_type')之前添加
通过query_posts,您可以轻松地修改您的循环。
编辑:
要具体检索一个post而不是循环,请使用get_posts。
$posts = get_posts('posts_per_page=1&post_type=my_custom_post_type');
//do not use reserved variable name $post
foreach($posts as $single_post) setup_postdata($single_post);
//you can use the_title(), the_content()...https://stackoverflow.com/questions/20147438
复制相似问题