Skip to content

Instantly share code, notes, and snippets.

@robertdevore
Created October 19, 2023 22:50
Show Gist options
  • Save robertdevore/67870195faab9e1799a36365661f6175 to your computer and use it in GitHub Desktop.
Save robertdevore/67870195faab9e1799a36365661f6175 to your computer and use it in GitHub Desktop.
<?php
/**
* Get media ID from URL
*
* @param string $image_url The image URL - https:// ...
*
* @return int|null
*/
function get_media_id_from_url( $image_url ) {
global $wpdb;
// Prepare the SQL query using $wpdb->prepare() to prevent SQL injection
$sql = $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE guid = %s", $image_url );
// Use $wpdb->get_var() to execute the prepared query and retrieve the result.
$attachment_id = $wpdb->get_var( $sql );
// Return the attachment ID (or null if not found).
return $attachment_id;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment