Php 检查当前的PostWordPress

Php 检查当前的PostWordPress,php,wordpress,conditional,Php,Wordpress,Conditional,我已经注册了一个自定义帖子类型,我想在我的存档文件myCPT.php中检索当前发布的帖子。 以下是my archive-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');

我已经注册了一个自定义帖子类型,我想在我的存档文件myCPT.php中检索当前发布的帖子。 以下是my archive-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');

 }

我怎样才能在这个循环中添加一个条件来检查当前发布的帖子并只检索一篇(最近的一篇)?这可能吗?如果是这样的话,我该怎么做呢?

在循环中,您只能获得已发布的帖子,因此这不是您的问题

如果您想要最新发布的帖子,请在
If(have_posts())
函数
query_posts('posts_per_page=1&order=DESC&orderby=date&post_type=my_custom_post_type')之前添加

通过,您可以轻松修改循环

编辑:

具体检索一篇文章而不是循环使用


我们可以在wp_查询参数中直接检索筛选后的选项

<?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();?>

/*标题*/
/*图像*/
因此,不需要在循环内部进行过滤。
希望这能有所帮助。

如果我使用它,将只检索最近发布的帖子?我尝试过这个方法,但对我来说不太好,它从默认的博客帖子中检索最后一篇帖子,而不是从我的CPT,它还为其他帖子添加了一个分页。若要检索CPT,请添加到查询帖子参数
&帖子类型=我的自定义帖子类型
。我不能百分之百确定,在使用循环时是否可以禁用显示分页链接(除去分页代码除外),您可以尝试
&paged=0
&paged=1
。无论如何,请检查我的编辑,我喜欢另一种解决方案,在这种情况下,它可能对您很有用。那么,我应该在哪里添加这个呢?在
if(have_posts()){
之前,或者在
内部,而(have_posts()){
。我想显示帖子,忘记只检索缩略图和标题。从
if(have_posts…
)删除整个循环
,基本上是“如果结束”的花括号,用我提供的代码替换它(
get_posts…
)。我假设您能够处理foreach循环的其余部分。最后,如果我写得不清楚,或者可能我没有理解您的全部意图,请将您的archive-cpt.php代码放在这里。
<?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();?>