【问题标题】:check for current post wordpress检查当前的帖子 wordpress
【发布时间】:2013-11-23 22:05:18
【问题描述】:

我已经注册了一个自定义帖子类型,并在我的存档-myCPT.php 中找到了我想检索只是当前发布的帖子。 这是我的 archive-myCPT.php 中的相关 sn-p:

if( have_posts() ){ 

$x = 1;
while ( have_posts() ){
 the_post(); 
  if ( 0 === (int) $post->post_parent) {
   get_template_part( 'inc/post-format/content-debate');

 }

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

【问题讨论】:

    标签: php wordpress conditional


    【解决方案1】:

    在循环中,您只会获得已发布的帖子,所以这不是您关心的问题。

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

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

    编辑:

    要专门检索一篇帖子而不是循环使用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()...
    

    【讨论】:

    • 如果我使用它,将只检索最近发布的帖子?
    • 我已经尝试过了,但对我不好,它会从默认博客文章中检索最后一篇文章,而不是从我的 CPT 中检索最后一篇文章,它还为其他文章添加了分页。
    • 要检索 CPT,添加到 query_posts 参数 &post_type=my_custom_post_type。我不确定是否可以在使用循环时禁用显示分页链接,(除了删除分页代码)您可以尝试&paged=0&paged=1。无论如何,请检查我的编辑,我喜欢在这种情况下可能对您有用的另一种解决方案。
    • 那么我应该在哪里添加这个?在if( have_posts() ){ 之前或while ( have_posts() ){ 内部。我想显示帖子,忘记只检索缩略图和标题。
    • 删除从if( have_posts...} 的整个循环,基本上是“if 结束”大括号,并将其替换为我提供的代码 (get_posts...)。我假设您能够处理 foreach 循环的其余部分。最后,如果我写得不清楚,或者我没有完全理解您的意图,请将您的archive-cpt.php代码放在这里。
    【解决方案2】:

    我们可以直接检索后过滤 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();?>
    

    因此不需要在循环内进行过滤。 希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2011-06-21
      • 2022-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多