Timber\PostCollection::maybe_set_preview PHP Method

maybe_set_preview() public static method

public static maybe_set_preview ( array $posts ) : array
$posts array
return array
    public static function maybe_set_preview($posts)
    {
        if (is_array($posts) && isset($_GET['preview']) && $_GET['preview'] && isset($_GET['preview_id']) && $_GET['preview_id'] && current_user_can('edit_post', $_GET['preview_id'])) {
            // No need to check the nonce, that already happened in _show_post_preview on init
            $preview_id = $_GET['preview_id'];
            foreach ($posts as &$post) {
                if (is_object($post) && $post->ID == $preview_id) {
                    // Based on _set_preview( $post ), but adds import_custom
                    $preview = wp_get_post_autosave($preview_id);
                    if (is_object($preview)) {
                        $preview = sanitize_post($preview);
                        $post->post_content = $preview->post_content;
                        $post->post_title = $preview->post_title;
                        $post->post_excerpt = $preview->post_excerpt;
                        $post->import_custom($preview_id);
                        add_filter('get_the_terms', '_wp_preview_terms_filter', 10, 3);
                    }
                }
            }
        }
        return $posts;
    }

Usage Example

Example #1
0
 /**
  * @param mixed $query
  * @param string|array $PostClass
  * @return array|bool|null
  */
 public static function get_post($query = false, $PostClass = '\\Timber\\Post')
 {
     // if a post id is passed, grab the post directly
     if (is_numeric($query)) {
         $post_type = get_post_type($query);
         $PostClass = PostGetter::get_post_class($post_type, $PostClass);
         $post = new $PostClass($query);
         // get the latest revision if we're dealing with a preview
         $posts = PostCollection::maybe_set_preview(array($post));
         if ($post = reset($posts)) {
             return $post;
         }
     }
     $posts = self::get_posts($query, $PostClass);
     if ($post = reset($posts)) {
         return $post;
     }
 }