Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.