WordPress.org

Support

Support » How-To and Troubleshooting » [Resolved] Got pre_get_posts to work for attachment display but now drafts showing too

[Resolved] Got pre_get_posts to work for attachment display but now drafts showing too

  • So I’m almost there with the concept of using pre_get_posts() to display attachments in Tag and Category taxonomy pages, however, the tax pages are also displaying Private and Draft Posts (along with Published Posts and Attachments).

    This is the code I have so far, adapted from many forum posts and the web:

    function add_attachments_to_media_query( $query ) {
    
    	if ( ! is_admin() && $query->is_main_query() && is_category() || is_tag() && empty( $query->query_vars['suppress_filters']) ) {
    
    	$query->set('post_type', array( 'post', 'attachment' ) );
    
    	if( $query->query_vars['post_type'] == 'attachment' ) {
    		$query->set('post_status', array( 'published', 'any' ) );
    	} elseif ( $query->query_vars['post_type'] == 'post' ) {
    		$query->set('post_status', 'published' );
    	} else {
    		$query->set('post_status', 'published' );
    	}
    	}
    return $query;
    }
    add_filter('pre_get_posts', 'add_attachments_to_media_query', 1);

    Any ideas on I went wrong with the code? Sorry all the questions, I’m very new to coding outside of basics. Thanks!

Viewing 4 replies - 1 through 4 (of 4 total)
  • I updated the code to be cleaner. Here’s what I have now:

    function custom_query( $query ) {
    
    	if ( ! is_admin() && $query->is_main_query() && is_category() || is_tag() ) {
    
    		$query->set('post_type', array( 'post', 'attachment' ) );
    
    			if( is_attachment() ) {
    				$postype = 'inherited';
    			} else {
    				$postype = 'published';
    			}
    	$query->set('post_status', $postype );
    	}
    	return $query;
    }
    add_filter('pre_get_posts', 'custom_query', 1);

    No answers so closing!

    Did you resolve this? I’m having the same issue.

    esmi

    @esmi

    Forum Moderator

    @jairus: If you require assistance then, as per the Forum Welcome, please post your own topic.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘[Resolved] Got pre_get_posts to work for attachment display but now drafts showing too’ is closed to new replies.
Skip to toolbar