Skip to content

Instantly share code, notes, and snippets.

@YOzaz
Created December 3, 2018 12:59
Show Gist options
  • Save YOzaz/9c66a2940a042d44d4700e982c491444 to your computer and use it in GitHub Desktop.
Save YOzaz/9c66a2940a042d44d4700e982c491444 to your computer and use it in GitHub Desktop.
Check if image exists - REGEX optimization
<?php
global $wpdb;
$query = 'SELECT `wp_posts`.`ID`, `wp_posts`.`guid`, `wp_postmeta`.`meta_value`
FROM `wp_posts`, `wp_postmeta`
WHERE `post_type` = "attachment"
AND `wp_posts`.`ID` = `wp_postmeta`.`post_id`
AND `wp_postmeta`.`meta_key` = "_wp_attachment_metadata"
AND `wp_postmeta`.`meta_value` REGEXP \'^a:[[:alnum:]]+:{s:5:"width";i:$$$PIXELS_WIDTH$$;s:6:"height";i:$$$PIXELS_HEIGHT$$$;s:4:"file";s:[[:alnum:]]+:"(.*?/|)$$$FILENAME$$$"\'';
$query = str_replace('$$$PIXELS_WIDTH$$$', $width, $query);
$query = str_replace('$$$PIXELS_HEIGHT$$$', $height, $query);
$query = str_replace('$$$FILENAME$$$', $filename, $query);
$results = $wpdb->get_results( $query, OBJECT );
if( count( $results ) > 0 )
// something found
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment