繁体   English   中英

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

[英]Using a custom Wordpress query to call 5 most recent posts

我正在尝试使用WP_query拉5个自定义帖子类型的最新帖子。 下面的代码看起来正确吗? 我是否需要在末尾使用wp_reset_postdata?

<?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 ?>

除非您在同一页面中再次使用WP_Query ,否则无需使用wp_reset_postdata() 需要使用wp_reset_postdata()来设置发布数据

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM