[php]
/**
* Get an attachment ID given a URL.
*
* @param string $url
*
* @return int Attachment ID on success, 0 on failure
*/
function get_attachment_id( $url ) {
$attachment_id = 0;
$dir = wp_upload_dir();
if ( false !== strpos( $url, $dir[‚baseurl‘] . ‚/‘ ) ) { // Is URL in uploads directory?
$file = basename( $url );
$query_args = array(
‚post_type‘ => ‚attachment‘,
‚post_status‘ => ‚inherit‘,
‚fields‘ => ‚ids‘,
‚meta_query‘ => array(
array(
‚value‘ => $file,
‚compare‘ => ‚LIKE‘,
‚key‘ => ‚_wp_attachment_metadata‘,
),
)
);
$query = new WP_Query( $query_args );
if ( $query->have_posts() ) {
foreach ( $query->posts as $post_id ) {
$meta = wp_get_attachment_metadata( $post_id );
$original_file = basename( $meta[‚file‘] );
$cropped_image_files = wp_list_pluck( $meta[’sizes‘], ‚file‘ );
if ( $original_file === $file || in_array( $file, $cropped_image_files ) ) {
$attachment_id = $post_id;
break;
}
}
}
}
return $attachment_id;
}
[/php]
Klicken Sie auf den unteren Button, um den Inhalt von wpscholar.com zu laden.
Related Articles
- Fix Elementor fixed Background sizing
- Cronjob Überlappung verhindern – flock()
- WordPress Update Hinweise deaktivieren
- WP Download Manager "attached file is missing/deleted" Fehler
- WordPress Staging: Uploads Ordner von Production Seite einlesen (per htaccess)
- WC Attribute Komma durch Linebreak ersetzen
- WordPress Autosave Intervall und Post Revisions
- Automatische WordPress Updates deaktivieren
- WPML wp-config.php Einstellungen
- Google Analytics Anonymize IP