WordPress wp_query and Loop


WP_Query provides numerous functions for common tasks within The Loop.

<?php 

// WP_Query arguments
$args = array(
	'p'                      => '1',  // Display Post by ID
	'name'                   => 'hello', // Display post by slugs.
	'page_id'                => '1', //Display page by ID.
	'pagename'               => 'pagename', //Display page by slugs.
	'post_parent'            => '10', //Display child-pages of a parent-page id
	'post_type'              => array( 'post' ),  //Display posts by post type
	'post_status'            => array( 'publish' ), //Display posts by (Publish, Future, Draft, Pending, Private, Trash, Auto-Draft, Inherit)
	'has_password'           => false, // Display posts with password default false
	'post_password'          => '123456', // Display posts which has password
	'author'                 => '1', //Display posts by author ID
 	'author_name'            => 'name',  //Display posts by author 'user_nicename'.
	's'                      => 'hello world', // Display post by keywords.
	'nopaging'               => false, // show pagination. default is true.
	'paged'                  => '10',  //Show posts in page number X.
	'posts_per_page'         => '10', //Number of post to show per page.
	'posts_per_archive_page' => '10', // Number of post to show per archive page.
	'ignore_sticky_posts'    => true, // Show or ignore sticky posts.
    'offset'                 => '0',  //Number of post to displace or pass over.default 0
	'order'                  => 'DESC', // Ascending or Descending order. default DESC
	'orderby'                => 'date', //Sort retrieved posts by.
	'perm'                   => 'manage_posts', //Display posts if user has the appropriate capability.
);

// The Query
$query = new WP_Query( $args );

// The Loop
if ( $query->have_posts() ) {
	while ( $query->have_posts() ) {
		$query->the_post();
		// do something
	}
} else {
	// no posts found
}

// Restore original Post Data
wp_reset_postdata()
?>

Scroll to Top