不幸的是,WordPress没有使用单独的功能来预览帖子。用户需要能够编辑帖子才能预览。如中所示the WP_Query::get_posts() method:
// User must have edit permissions on the draft to preview.
if ( ! current_user_can($edit_cap, $this->posts[0]->ID) ) {
$this->posts = array();
}
您可以使用
posts_results
过滤器(在处理未发布的帖子之前应用)和
the_posts
过滤器(在之后应用),如果用户是参与者,则重新填充posts数组。
请仔细检查这一点,以了解允许较低级别用户访问预览未发布内容的任何安全影响。
未经测试的示例:
class wpse_196050 {
protected $posts = array();
public function __construct() {
add_filter( \'posts_results\', array( $this, \'filter_posts_results\' ), 10, 2 );
add_filter( \'the_posts\', array( $this, \'filter_the_posts\' ), 10, 2 );
}
public function filter_posts_results( array $posts, WP_Query $query ) {
$this->posts = []; // Reset posts array for each WP_Query instance
if ( $query->is_preview ) {
$this->posts = $posts;
}
return $posts;
}
public function filter_the_posts( array $posts, WP_Query $query ) {
if ( ! empty( $this->posts ) && current_user_can( \'edit_posts\' ) ) {
$posts = $this->posts;
}
return $posts;
}
}
new wpse_196050;