1

I am extending the use of Media/"Attachments" so that they have a custom taxonomy of "Medium" and I can display taxonomy archives on the frontend. I'd only like the archive query to display ones with a published parent. This is because sometimes the parent post is set to "draft", or there is no parent at all yet, and I don't want attachments to appear on the taxonomy archive page until they have a parent and that parent is published.

I have a couple ideas on how this might work, but so far have not been able to succeed at any:

  1. extend Attachment post type statuses beyond "inherit", and update the status based on what's happening with their parent (i.e. if the parent is "draft", the attachment is also "draft" and won't show up publicly)
  2. modify the query_vars in my parse_query filter so that it excludes unattached media / attachments without a parent

My plugin code so far is below. This is functioning in that it's allowing me to have archive pages for my custom taxonomy "Medium":

/**
 * Allow Attachments to be queried so they appear on taxonomy archive pages
 * @link https://wordpress.stackexchange.com/a/31739
 */
function ahub_query_attachments() {

    global $wp_query;

    if ( is_tax('ahub_medium') ) {
        $wp_query->query_vars['post_type'] =  array( 'attachment' );
        $wp_query->query_vars['post_status'] = 'inherit';

        return $wp_query;
    }

}
add_action('parse_query', 'ahub_query_attachments');


/**
 * Allow "inherit" post status for Attachment to be queried, so they can be on archive pages
 * @link https://wordpress.stackexchange.com/a/373437
 */
function ahub_query_inherit_attachments( $query ) {

    if ( is_post_type_archive('attachment') && 'attachment' == $query->get('post_type') ) {
        $query->set( 'post_status', 'inherit' );
    }

    return $query;

}
add_action( 'pre_get_posts', 'ahub_query_inherit_attachments' , 10, 1);

How can I get media that's not attached to a published parent yet to not show up in my archives?

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.