Support » Plugins » Hacks » get the attachment only if the post status of the parent is published

  • Hello everybody.

    I have to made an attachment archive by custom taxonomy.
    I don’t know why the page of the term, like mysite.com/custom_taxonomy/attachment_term, doesn’t work.

    Anyway I decide to write a custom query by myself and run it inside a template page.
    It works, but I have a problem.
    When I get the attachments, I get all the of them, even if the parent is not published. This cause a 404 if someone clicks on them. Instead, if the post_parent is 0, with a click we arrive to the attachment page mysite.com/?attachment_id=x. Moreover if the attachment is regularly inside a post, it goes to mysite.com/post_name/attachment.

    So how can I check all of these and get the attachments with parent 0 or the parent Publish?

    Here’s the query right now

    $sql = "
    	SELECT p.*
    	FROM $wpdb->posts p
    	LEFT JOIN $wpdb->term_relationships r
    		ON r.object_id = p.ID
    	LEFT JOIN $wpdb->term_taxonomy t
    		ON t.term_taxonomy_id = r.term_taxonomy_id
    	LEFT JOIN $wpdb->terms te
    		ON te.term_id = t.term_id
    	WHERE te.slug = 'OneOfmMyTerms'
    ";

    thanks!!!

Viewing 2 replies - 1 through 2 (of 2 total)
  • Thread Starter somtam

    (@somtam)

    ok, this is where I arrived, and it works, but it makes one query for each attachment, so I think a high consuming method.

    I go to alter the main query with pre_get_posts()

    function my_show_tax_attachments( $query ) {
        if ( $query->is_tax('myTaxonomy') && $query->is_main_query() ) {
            $query->set( 'post_status', 'inherit' );
        }
    }
    add_action( 'pre_get_posts', 'my_show_tax_attachments' );

    then on the taxonomy-myTaxonomy.php template

    <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
    
    <?php
    
       if($post->post_parent > 0) {
          $att_post_parent = get_post( $post->post_parent );
          if( $att_post_parent != null && $att_post_parent->post_status =='publish' ) {
                print_attachment_preview($post);
          }
       } else {
          print_attachment_preview($post);
       }
    ?>
    <?php endwhile; else: ?>
       <h2>No Results</h2>
    <?php endif; ?>

    There’s so a way to check it with the main query?
    thanks!

    I am looking for the same, get attachments only if the parent post is published. This works, but I am also wondering if you found a more efficient way to do that.

    Thanks.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘get the attachment only if the post status of the parent is published’ is closed to new replies.