How to fetch only media that was already attached to a post/page?

Situation: my client has this simple gallery built with WP_Query showing the latest media added to the site:

$cola = new WP_Query(
    array(
    'post_type' => 'attachment',
    'post_status' => 'inherit',
    'posts_per_page' => 15,
    'post_mime_type' => 'image/jpeg',
    'orderby' => 'date'
    ));

that’s working perfect. Except for now we’re using AdRotate and want to display ads on the website, but we don’t want these ads to be added to the query above.

Read More

A simple solution for this would be to only fetch media that is attached to a post/page, since ads never get attached to anything. This would be achievable by using post_parent: array(_of_all_post_ids) – except that we already have about 4k posts now, so this is definitely not a good approach.

Any ideas how to go about that?

Note: my client is not a techie so this is why i’m ruling out using FTP to use the banner folder AdRotate creates on wp-content. For their planned use, the media gallery would be perfect for the ads.

Related posts

Leave a Reply

1 comment

  1. A similar approach to your post_parent idea is to add a filter to posts_where:

    function bbg_filter_out_non_attachments( $sql ) {
        global $wpdb;
    
        // Maybe do some conditional logic to decide whether to filter this query, then...
        return $sql . " AND $wpdb->posts.post_parent != 0 ";
    }
    add_filter( 'posts_where', 'bbg_filter_out_non_attachments' );
    

    Another technique is to do a manual query for post IDs with no post_parent, and then pass it to post__not_in:

    $ad_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_parent = 0 AND post_type = 'attachment'" ) );
    $query_args['post__not_in'] = $ad_ids;
    // etc
    

    If you don’t like the idea of mucking around directly with SQL, you could also piece something together that adds a piece of postmeta to every item uploaded through the Media Library (instead of on a new post), and then include a meta_query parameter in your WP_Query. Note, however, that this isn’t going to be anywhere near as efficient as simply looking for post_parent (which is data that already exists, and does not require a table join).