
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.
Returns
Array|Object|null. The result of a database query. Returns:
- An array of objects – when
$output = OBJECT
orOBJECT_K
. - An array of arrays – when
$output = ARRAY_A
orARRAY_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.
Using
global $wpdb; $wpdb->get_results( $query, $output );
$query(string)
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
$
output(constant/string)
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
Examples
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
<?php $fivesdrafts = $wpdb->get_results( "SELECT * FROM $wpdb->posts WHERE post_status = 'draft' AND post_author = 5"); if( $fivesdrafts ) : foreach( $fivesdrafts as $post ){ setup_postdata($post); ?> <h2><a href="<?php the_permalink(); ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>"><?php the_title(); ?></a></h2> <?php } else : ?> <h2> Не найдено</h2> <?php endif; ?>
Leave a Reply