WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] [closed] Got pre_get_posts to work for attachment display but now drafts showing too (5 posts)

  1. openwp3
    Member
    Posted 1 year ago #

    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!

  2. openwp3
    Member
    Posted 1 year ago #

    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);
  3. openwp3
    Member
    Posted 1 year ago #

    No answers so closing!

  4. Jairus
    Member
    Posted 7 months ago #

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

  5. esmi
    Forum Moderator
    Posted 7 months ago #

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

Topic Closed

This topic has been closed to new replies.

About this Topic