The get_posts_by_author_sql() WordPress PHP function retrieves the SQL query for posts based on capability, author, and type.
Usage
Here’s a generic example of how to use the function:
$where = get_posts_by_author_sql('post'); echo $where;
Parameters
- $post_type (string|array): Required. Single post type or an array of post types.
- $full (bool): Optional. Returns a full WHERE statement instead of just an ‘andalso’ term. Default: true.
- $post_author (int): Optional. Query posts having a single author ID. Default: null.
- $public_only (bool): Optional. Only return public posts. Skips cap checks for $current_user. Default: false.
More information
See WordPress Developer Resources: get_posts_by_author_sql
Note: The full option set to false currently doesn’t return the post filter as you would expect. See this patch and test for more info: https://core.trac.wordpress.org/ticket/30354
Examples
Get posts by author
This example retrieves posts by a specific author with ID 5:
$author_id = 5; $where = get_posts_by_author_sql('post', true, $author_id); echo $where;
Get public posts only
This example retrieves only public posts:
$public_only = true; $where = get_posts_by_author_sql('post', true, null, $public_only); echo $where;
Get posts of custom post type
This example retrieves posts of a custom post type called ‘book’:
$where = get_posts_by_author_sql('book'); echo $where;
Get posts of multiple post types
This example retrieves posts of multiple post types, ‘post’ and ‘page’:
$post_types = array('post', 'page'); $where = get_posts_by_author_sql($post_types); echo $where;
Get post ID by title
This example retrieves the post ID of a post with the title “Hello world!”:
$where = get_posts_by_author_sql('post'); global $wpdb; $query = "SELECT ID FROM $wpdb->posts $where AND post_title = %s"; $post_id = $wpdb->get_var($wpdb->prepare($query, 'Hello world!')); echo $post_id;