• Resolved ffd8

    (@ffd8)


    I’ve tried searching for this and found a handful of resources, however I still just can’t get it to work, so perhaps someone can spot an obvious mistake in the code?

    Essentially, I’m scraping all uploaded/attachment images between a range of dates, however I would like to exclude those images which were part of particular categories. I’ve tried using both the cat=-#, or category__not_in, however it’s still coming up blank. Here’s the crucial snippet of code where the magic isn’t happening:

    function exclude_category($query) {
        if ( $query->is_home() ) {
            $query->set('cat', '-1765,-2491,-2744,-2867,-3107');
        }
        return $query;
    }
    
    add_filter('pre_get_posts', 'exclude_category');
    
    $media_query = new WP_Query(array(
        'post_type' => 'attachment',
        'post_mime_type' =>'image',
        'post_status' => 'inherit',
        'posts_per_page' => -1,
        // 'cat' => array(-1765,-2491,-2744,-2867,-3107), // tried also
    ));
    remove_filter( 'posts_where', 'filter_where' );
    
    foreach ($media_query->posts as $post) {
        $img = wp_get_attachment_image_src($attachment_id, $imgSize);
        echo '<img src="'.$img[0].'" id="">';
    }

    I’m wondering if it might not be possible to filter from which posts, when doing this post_type or mime_type, and is gathering all uploads? or…

    Tried everything on: https://codex.www.ads-software.com/Class_Reference/WP_Query
    Thanks in advance for any advice!

Viewing 1 replies (of 1 total)
  • Thread Starter ffd8

    (@ffd8)

    Solved the problem [ignore wrong ‘remove_filter’ above]! It seems to be true that when doing attachments/images query, it ignores all filtering of categories I threw at it… Instead, one can ask for the image object’s post_parent, then do an in_category() test to exclude the ones to be ignored:

    $ads = array(2,4); // list of cats to exclude
    $media_query = new WP_Query(array(
      	'post_type' => 'attachment',
    	'post_mime_type' =>'image',
    	'post_status' => 'inherit',
    	'posts_per_page' => -1,
    ));
    
    foreach ($media_query->posts as $post) {
    	if (!in_category($ads, $post->post_parent)){
    		$img = wp_get_attachment_image_src($post->ID, $imgSize)[0];
    		echo '<img src="'.$img.'" id="">';
    	}
    }

    Hope that helps someone trying to scrape their images too…

Viewing 1 replies (of 1 total)
  • The topic ‘Scraping images, excluding categories’ is closed to new replies.