Bài tập new wp_Query trong wordpress

Lấy 10 bài viết mới nhất trong wordpress

<?php 
  $args = array(
    'posts_per_page' => 10,
    'post_type'   => 'post',
    'post_status' => 'publish'
  );
  $the_query = new WP_Query( $args );
?>
<?php if( $the_query->have_posts() ): ?>
<?php while( $the_query->have_posts() ) : $the_query->the_post(); ?>
  // Thông tin cần lấy của 1 bài viết
<?php endwhile; ?>
<?php endif; ?>
<?php wp_reset_query(); ?>

Lấy 5 bài viết của chuyên mục tin tức, giả sử chuyên mục tin tức có id là 1

<?php 
  $args = array(
    'posts_per_page'  => 5,
    'post_type'       => 'post',
    'post_status'     => 'publish',
    'cat'             => 1
  );
  $the_query = new WP_Query( $args );
?>
<?php if( $the_query->have_posts() ): ?>
<?php while( $the_query->have_posts() ) : $the_query->the_post(); ?>
  // Thông tin cần lấy của 1 bài viết
<?php endwhile; ?>
<?php endif; ?>
<?php wp_reset_query(); ?>

Lấy 10 bài viết ngẫu nhiên trong wordpress

<?php 
  $args = array(
    'posts_per_page'  => 10,
    'post_type'       => 'post',
    'post_status'     => 'publish',
    'orderby'         => 'rand'
  );
  $the_query = new WP_Query( $args );
?>
<?php if( $the_query->have_posts() ): ?>
<?php while( $the_query->have_posts() ) : $the_query->the_post(); ?>
  // Thông tin cần lấy của 1 bài viết
<?php endwhile; ?>
<?php endif; ?>
<?php wp_reset_query(); ?>

Last updated