TODO: To change the header's content go to Dr.Explain menu Options : Project Settings : HTML (CHM) Export : Setup HTML Template and Layout
×
Menu
Index

Truy vấn dữ liệu posts (WP_Query, get_posts, query_posts)

- Lấy dữ liệu posts với WP_Query, get_posts, main query:
+ get_posts example
$args = array( 'posts_per_page' => 5, 'offset'=> 1, 'category' => 1 );
$myposts = get_posts( $args );
foreach ( $myposts as $post ) :   #load global $post
      setup_postdata( $post );
      // template tag
      the_title();
 
      // post content
      the_content();
      //use the Read More functionality
      the_content('Read the full post »');  
      ...
      //access table columns name for any posts
      $post->ID;
      $post->post_title;
      $post->post_content;
  ?>
   <li>
         <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</li>
<?php
endforeach;
wp_reset_postdata();
 
Bạn cũng có thể truyền tham số dạng chuỗi:
$data = get_posts('posts_per_page=5&offset=1&category=1');
 
+ Main query:
//set query args
query_posts('posts_per_page=5');
//loop posts
while(have_posts()):
   the_post();
    ...
endwhile;
// Reset Query
wp_reset_query();
 
Xác định query ở trang hiện tại, từ đó lọc thêm điều kiện để giới hạn kết quả cuối cùng.
global $query_string;
query_posts($query_string. '&posts_per_page=5&order=ASC');
 
Chú ý: khuyến khích sử dụng filter 'pre_get_posts' không nên chuỗi query đơn lẻ ở các trang bạn có ý định sửa đổi kết quả posts. Viết vào file functions.php
function five_posts_on_homepage( $query ) {
    if ( $query->is_home() && $query->is_main_query() ) {
        $query->set( 'posts_per_page', 5 );
    }
}
add_action( 'pre_get_posts', 'five_posts_on_homepage' );
 
Sử dụng kiểu mảng làm tham số query_posts.
global $wp_query;
$args = array_merge( $wp_query->query_vars, array( 'post_type' => 'product' ) );
query_posts( $args );
 
Tham số:
$args = array(
    'post_type'=> 'movie',  //post type
     'order'    => 'ASC'   //order
);
query_posts( $args );
 
+ WP_Query
<?php
// example args
$args = array( 'posts_per_page' => 3 );
 
// the query
$the_query = new WP_Query( $args );
<?php while ( $the_query->have_posts() ) : $the_query->the_post();
     the_title();
     the_excerpt();
 
     the_ID();
     get_the_ID();
     $query->post->ID;       //trả về ID của post ~ the_ID()
endwhile;
?>
 
 
Made with help of Dr.Explain

Unregistered version