WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Post Parent Status for Attachments (5 posts)

  1. elizabethannedesigns
    Member
    Posted 1 year ago #

    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!!

  2. keesiemeijer
    moderator
    Posted 1 year ago #

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

    @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!

  4. keesiemeijer
    moderator
    Posted 1 year ago #

    You're welcome. I'm glad you've got it resolved :-)

  5. yunieskid
    Member
    Posted 11 months ago #

    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!

Topic Closed

This topic has been closed to new replies.

About this Topic