根据功能,作者和类型检索post SQL。

原型

get_posts_by_author_sql( array|string $post_type, bool $full = true, int $post_author = null, bool $public_only = false )

参数

$post_type (array|string) (Required) 单一帖子类型或一组帖子类型。

$full (bool) (Optional)  返回一个完整的WHERE语句,而不仅仅是一个’andalso’项。

$post_author (int) (Optional)  查询具有单个作者ID的帖子。

$public_only (bool) (Optional)  只返回公开帖子。跳过$ current_user的上限检查。

返回值

(string)  可以添加到查询的SQL WHERE代码。

源文件

路径:wp-includes/post.php

<?php
...
function get_posts_by_author_sql( $post_type, $full = true, $post_author = null, $public_only = false ) {
	global $wpdb;
	if ( is_array( $post_type ) ) {
		$post_types = $post_type;
	} else {
		$post_types = array( $post_type );
	}
	$post_type_clauses = array();
	foreach ( $post_types as $post_type ) {
		$post_type_obj = get_post_type_object( $post_type );
		if ( ! $post_type_obj ) {
			continue;
		}
		/**
		 * Filters the capability to read private posts for a custom post type
		 * when generating SQL for getting posts by author.
		 *
		 * @since 2.2.0
		 * @deprecated 3.2.0 The hook transitioned from "somewhat useless" to "totally useless".
		 *
		 * @param string $cap Capability.
		 */
		if ( ! $cap = apply_filters( 'pub_priv_sql_capability', '' ) ) {
			$cap = current_user_can( $post_type_obj->cap->read_private_posts );
		}
		// Only need to check the cap if $public_only is false.
		$post_status_sql = "post_status = 'publish'";
		if ( false === $public_only ) {
			if ( $cap ) {
				// Does the user have the capability to view private posts? Guess so.
				$post_status_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 ) {
					$post_status_sql .= " OR post_status = 'private' AND post_author = $id";
				} elseif ( $id == (int) $post_author ) {
					$post_status_sql .= " OR post_status = 'private'";
				} // else none
			} // else none
		}
		$post_type_clauses[] = "( post_type = '" . $post_type . "' AND ( $post_status_sql ) )";
	}
	if ( empty( $post_type_clauses ) ) {
		return $full ? 'WHERE 1 = 0' : '1 = 0';
	}
	$sql = '( '. implode( ' OR ', $post_type_clauses ) . ' )';
	if ( null !== $post_author ) {
		$sql .= $wpdb->prepare( ' AND post_author = %d', $post_author );
	}
	if ( $full ) {
		$sql = 'WHERE ' . $sql;
	}
	return $sql;
}
...
?>

其他

英文文档:https://developer.wordpress.org/reference/functions/get_posts_by_author_sql/