Created
September 10, 2019 02:13
-
-
Save johnalarcon/770ea92eba16a9661deafb31a941a6d5 to your computer and use it in GitHub Desktop.
Retrieve specific fields from an attachment when only a value is known.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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