dsx5201 2018-05-06 04:29
浏览 30

使用自定义Wordpress查询来调用5个最近的帖子

I am trying to pull the 5 most recent posts of a custom post type using a WP_query. Does the code below look correct? And do I need to use wp_reset_postdata at the end?

<?php 
  $args = array(
    'post_type'  => 'webinar_post',
    'post_status' => 'publish',
    'posts_per_page' => 5,
    'orderby' => 'post_date',
    'order' => 'DESC',
  );
  $most_recent = new WP_Query( $args );
?>

<?php if( $most_recent->have_posts() ) ?>

  <?php while( $most_recent->have_posts() ) : $most_recent->the_post() ?>
   <div class="webinar">
    <h2><?php echo get_the_title(); ?> </h2>
    <h3><?php echo get_the_date(); ?></h3>
    <p><?php echo get_the_excerpt(); ?></p>
</div>
  <?php endwhile; ?>

<?php endif ?>
  • 写回答

1条回答 默认 最新

  • dsxrq28228 2018-05-06 07:13
    关注

    You don't need to use wp_reset_postdata() unless you are using WP_Query again in the same page. Usage of wp_reset_postdata() is need to set the post data back

    Example

    <?php
    // The 1st Query
    $args = [
        'post_type'  => 'webinar_post',
        'post_status' => 'publish',
        'posts_per_page' => 5,
        'orderby' => 'post_date',
        'order' => 'DESC',
    ];
    $most_recent = new WP_Query( $args );
    if ( $most_recent->have_posts() ) {
        // The Loop
        while ( $most_recent->have_posts() ) { $most_recent->the_post();
            // your code
        }
        // Restore original Post Data
        wp_reset_postdata();
    }
    
    // Updating `$args`
    $args['orderby'] = 'post_title'
    $args['order'] = 'ASC'
    
    /* The 2nd Query */
    $most_recent2 = new WP_Query( $args );
    if ( $most_recent2->have_posts() ) {
        // The 2nd Loop
        while ( $most_recent2->have_posts() ) { $most_recent2->the_post();
            // your code
        }
        // Restore original Post Data
        wp_reset_postdata();
    }
    ?>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用