WordPress

WordPress

get_posts( array $args = null )

Retrieves an array of the latest posts, or posts matching the given criteria.

get_posts() Function Parameters

$args = array(
	'numberposts'	=> 20,
	'category'		=> 4
);
$my_posts = get_posts( $args );

if( ! empty( $my_posts ) ){
	$output = '<ul>';
	foreach ( $my_posts as $p ){
		$output .= '<li><a href="' . get_permalink( $p->ID ) . '">' 
		. $p->post_title . '</a></li>';
	}
	$output .= '<ul>';
}

Using WordPress get_posts is a two-step process:

  • First, you have to build your custom query. Actually, it won’t look like a MySQL query, and you won’t write any SELECT statement. You just need to define an array of parameters and pass it to the get_posts function. WordPress converts that array into a real and secure MySQL query, runs it against the database, and returns an array of posts.
  • Second, you have to traverse the result set returned by get_posts with a for each cycle.

How To Use Parameters to Build Simple Queries

  • author (int) – author ID
  • author_name (string) – author’s user_nicename
  • author__in (array) – an array of multiple authors’ IDs
  • author__not_in (array) – an array of multiple authors’ IDs to be excluded from the result set

The WP_Post Object

  • ID: ID of the post
  • post_author: Author name of the post
  • post_type: Type of the post
  • post_title: Title of the post
  • post_date: Date on which post was published. Format: 0000-00-00 00:00:00
  • post_content: Content of the post.
  • post_status: Status of the post

Random Posts

<?php
  $args = array("posts_per_page" => 1, "orderby" => "rand");
  $posts_array = get_posts($args);
  foreach($posts_array as $post)
  {
    echo "<h1>" . $post->post_title . "</h1><br>";
    echo "<p>" . $post->post_content . "</p><br>";
  } 
?>

Most Popular Posts

<?php
	$args = array("posts_per_page" => 10, "orderby" => "comment_count");
	$posts_array = get_posts($args);
	foreach($posts_array as $post)
	{
	  echo "<h1>" . $post->post_title . "</h1><br>";
	  echo "<p>" . $post->post_content . "</p><br>";
	} 
?>