WordPress get_results

Gets all data of the specified query (all rows and columns). The result is returned as an array. Each element of the array is an object with data of a separate table row.

{}This is a method of class: wpdb{}

There are no hooks.


Array|Object|null. The result of a database query. Returns:

  • An array of objects – when $output = OBJECT or OBJECT_K.
  • An array of arrays – when $output = ARRAY_A or ARRAY_N.
  • array() – when no rows were found by the query or a query error.
  • NULL – when query empty string or wrong output type ($output_type) is passed.


global $wpdb;
$wpdb->get_results( $query, $output );

The query to be executed.

You can set this parameter to null, then the function will return the result of the last query that was made.

Default value: null


This flag tells how data must be returned. There are 4 possible ways:

  • OBJECT – will return an array of objects with numeric keys – array elements will be table row objects – [ 0 => object ].
  • OBJECT_K – similar to previous one, only indexes of main array will contain values of first column of query result – [‘field’ => object ]. Pay attention, if there are the same values in index, then data will be overwritten.
  • ARRAY_N – returns an index array, each element of which will also be an index array – [ 0 => […] ].
  • ARRAY_A – returns an index array, each element of which will be an associative array, where the key will be the column name – [‘field’ => […] ].

Default: OBJECT


1. Let’s get the ID and titles of drafts whose author ID is 5 and display the titles of the posts.

$fivesdrafts = $wpdb->get_results( "SELECT ID, post_title FROM $wpdb->posts WHERE post_status = 'draft' AND post_author = 5" );
foreach ( $fivesdrafts as $fivesdraft ) {
echo $fivesdraft->post_title;

2. Print the links to the author’s drafts with ID = 5

$fivesdrafts = $wpdb->get_results( "SELECT * FROM $wpdb->posts WHERE post_status = 'draft' AND post_author = 5"); 
if( $fivesdrafts ) : 
 foreach( $fivesdrafts as $post ){
<h2><a href="<?php the_permalink(); ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>"><?php the_title(); ?></a></h2> 
else : 
<h2> Не найдено</h2> 
<?php endif; ?>

Leave a Reply

Your email address will not be published. Required fields are marked *

The site was created in 2010, with the goal: to share experiences related to WordPress.

Work on the site does not stop to this day: as forces are added articles, described the core and popular Themes.

Time has shown that the site helps many in their work and study of WordPress.