• Resolved elizabethannedesigns

    (@elizabethannedesigns)


    Hi all! Going crazy trying to work this out. I am using pre_get_posts to adjust the wordpress query for an attachment taxonomy. Attachments have the post_status of inherit, but by specifying that in my pre_get_posts I’m getting attachments for parent posts in draft and pending status. Any thoughts on how to restrict the results to only published parent posts?

    Thank you!!

Viewing 4 replies - 1 through 4 (of 4 total)
  • Moderator keesiemeijer

    (@keesiemeijer)

    The only way I could get it to work is with something similar to this in my functions.php:

    function attachment_query( $query ) {
      // not an admin page and is the main query
      if (!is_admin() && $query->is_main_query()){
    
          // wrap this up in a conditional for your attachment page
          $query->set('post_type', 'attachment');
          $query->set('post_status', 'inherit');
          $query->set('post_mime_type', 'image');
          $query->set('posts_per_page', 10);
          // add an extra filter for draft and pending parent posts
          add_filter('posts_where', 'new_posts_where');
    
      }
    }
    add_action( 'pre_get_posts', 'attachment_query' );
    
    function new_posts_where ($where) {
    	global $wpdb;
    	$where .= " AND $wpdb->posts.post_parent NOT IN (SELECT wp_posts.ID FROM wp_posts WHERE $wpdb->posts.post_status = 'draft' OR $wpdb->posts.post_status = 'pending')";
    	return $where;
    }

    Thread Starter elizabethannedesigns

    (@elizabethannedesigns)

    @keesiemeijer Bless You! This is working on my test site (I added an OR for post_status of ‘future’ as well). Going to try it in production tonight. Thanks again!

    Moderator keesiemeijer

    (@keesiemeijer)

    You’re welcome. I’m glad you’ve got it resolved ??

    Hello, this function seems to work perfectly, but i have a doubt, i would like to use it in the loop, use the loop taking into account to filter the images only if the post parent is publish.
    Thanks!

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Post Parent Status for Attachments’ is closed to new replies.