WordPress Version: 3.7
/**
* Retrieve the post SQL based on capability, author, and type.
*
* @see get_private_posts_cap_sql() for full description.
*
* @since 3.0.0
* @param string $post_type Post type.
* @param bool $full Optional. Returns a full WHERE statement instead of just an 'andalso' term.
* @param int $post_author Optional. Query posts having a single author ID.
* @param bool $public_only Optional. Only return public posts. Skips cap checks for $current_user. Default is false.
* @return string SQL WHERE code that can be added to a query.
*/
function get_posts_by_author_sql($post_type, $full = true, $post_author = null, $public_only = false)
{
global $wpdb;
// Private posts
$post_type_obj = get_post_type_object($post_type);
if (!$post_type_obj) {
return $full ? 'WHERE 1 = 0' : ' 1 = 0 ';
}
// This hook is deprecated. Why you'd want to use it, I dunno.
if (!$cap = apply_filters('pub_priv_sql_capability', '')) {
$cap = $post_type_obj->cap->read_private_posts;
}
if ($full) {
if (null === $post_author) {
$sql = $wpdb->prepare('WHERE post_type = %s AND ', $post_type);
} else {
$sql = $wpdb->prepare('WHERE post_author = %d AND post_type = %s AND ', $post_author, $post_type);
}
} else {
$sql = '';
}
$sql .= "(post_status = 'publish'";
// Only need to check the cap if $public_only is false
if (false === $public_only) {
if (current_user_can($cap)) {
// Does the user have the capability to view private posts? Guess so.
$sql .= " OR post_status = 'private'";
} elseif (is_user_logged_in()) {
// Users can view their own private posts.
$id = get_current_user_id();
if (null === $post_author || !$full) {
$sql .= " OR post_status = 'private' AND post_author = {$id}";
} elseif ($id == (int) $post_author) {
$sql .= " OR post_status = 'private'";
}
// else none
}
// else none
}
$sql .= ')';
return $sql;
}