Skip to content

Instantly share code, notes, and snippets.

@johnalarcon
Created September 10, 2019 02:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnalarcon/770ea92eba16a9661deafb31a941a6d5 to your computer and use it in GitHub Desktop.
Save johnalarcon/770ea92eba16a9661deafb31a941a6d5 to your computer and use it in GitHub Desktop.
Retrieve specific fields from an attachment when only a value is known.
function codepotent_get_attachment_field($select, $where, $value) {
// Bring database object into scope.
global $wpdb;
// Assemble the query.
$sql = "SELECT %s FROM $wpdb->posts WHERE %s='%s';";
// Run the query.
$result = $wpdb->get_var($wpdb->prepare($sql, $select, $where, trim($value)));
// Error or empty result? Bail.
if (is_wp_error($result) || empty($result)) {
return 0;
}
// Return the value.
return $result;
}
// Scenario: you need to find the ID of an image that was uploaded through
// the ClassicPress media uploader, but, only have the URL of the full image.
// Solution: return the ID field where guid matches the image URL.
$select = 'ID';
$where = 'guid';
$value = 'https://codepotent.com/wp-content/uploads/2019/07/valves-at-factory.jpg';
$attachment_id = codepotent_get_attachment_field($select, $where, $value);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment