Attention Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

Function Reference/get posts by author sql


Retrieve the post SQL based on capability, author, and type.

This function provides a standardized way to appropriately select on the post_status of a post type. The function will return a piece of SQL code that can be added to a WHERE clause; this SQL is constructed to allow all published posts, and all private posts to which the user has access.

<?php get_posts_by_author_sql$post_type$full$post_author$public_only); ?>


(string) (required) Post type.
Default: None
(boolean) (optional) Optional. Returns a full WHERE statement instead of just an 'andalso' term.
Default: true
(integer) (optional) Query posts having a single author ID.
Default: null
(bool) (optional) Only return public posts. Skips capability checks for the current user.
Default: false

Return Values

SQL WHERE code that can be added to a query.


$where = get_posts_by_author_sql( 'post' );
echo $where;

// user logged in: WHERE post_type = 'post' AND (post_status = 'publish' OR post_status = 'private')
// user not logged in: WHERE post_type = 'post' AND (post_status = 'publish')

// get post ID with title "Hello world!" query
global $wpdb;
$query = "SELECT ID FROM $wpdb->posts $where AND post_title = %s";
$post_id = $wpdb->get_var( $wpdb->prepare( $query, 'Hello world!' ) );

Change Log

Since: 3.0

Source File

get_posts_by_author_sql() is located in wp-includes/post.php