WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Problem filtering query to allow displaying drafts (even for not logged users) (2 posts)

  1. grosbouff
    Member
    Posted 2 years ago #

    Hi, I have a draft post ?p=7149.
    I would like to be able to see it even if i'm not logged on the website.

    function my_get_posts($query) {
    
      if (is_admin())return $query;
      if($query->query_vars['suppress_filters'] )return $query;
    
      $query->set('post_status','any');
    
      return $query;
    }
    add_filter( 'pre_get_posts', 'my_get_posts' );

    When I print the query, I got

    SELECT wp_posts.* FROM wp_posts WHERE 1=1 AND wp_posts.ID = 7149 AND wp_posts.post_type = 'post' AND (wp_posts.post_status <> 'trash' AND wp_posts.post_status <> 'auto-draft') ORDER BY wp_posts.post_date DESC

    which returns me results in phpmyadmin.

    But when I access ?p=7149 I got a PAGE NOT FOUND.
    Seems is_404 is set to TRUE.
    When accessing ?post_type=post; the post #7149 is shown.
    So seems it has something to see with the fact that we are viewing a single post.

    Does anybody have an idea about this ?

    Thanks !

    http://pastie.org/3432690

  2. grosbouff
    Member
    Posted 2 years ago #

    I found out.
    WP hides posts with status = draft if we are not allowed to see them.

    Here's my solution :

    function guest_enable_hidden_single_post($query){
    
        if (is_user_logged_in()) return $query;
         //user is not logged
    
        if(!is_single()) return $query;
        //this is a single post
    
        if (!$query->is_main_query())return $query;
    	//this is the main query    
    
        $query->set( 'post_status',array('publish','pending','draft'));
        //allowed post statuses for guest
    
        return $query;
    
    }
    
    function guest_reload_hidden_single_post($posts){
        global $wp_query, $wpdb;
    
        if (is_user_logged_in()) return $posts;
        //user is not logged
    
        if(!is_single()) return $posts;
        //this is a single post
    
        if (!$wp_query->is_main_query())return $posts;
        //this is the main query
    
        if($wp_query->post_count) return $posts;
        //no posts were found
    
        $posts = $wpdb->get_results($wp_query->request);
    
        return $posts;
    }
    
    //allow guests to view single posts even if they have not post_status="publish"
    add_filter('pre_get_posts','guest_enable_hidden_single_post');
    
    //reload hidden posts
    add_filter('the_posts','guest_reload_hidden_single_post');

Topic Closed

This topic has been closed to new replies.

About this Topic