Obtener ID del attachment, thumbnail por url

Hay veces que necesitamos obtener el ID de un elemento del multimedia por la URL, tuve la necesidad cuando tenia un campo múltiple de tipo imagen en el cual tenia las url y queria obtener un tamaño personalizado que habia agregado en el functions

<?php 
/** obtener id por url */
function get_attachment_id_by_url( $url ) {
// Split the $url into two parts with the wp-content directory as the separator
$parsed_url = explode( parse_url( WP_CONTENT_URL, PHP_URL_PATH ), $url );

// Get the host of the current site and the host of the $url, ignoring www
$this_host = str_ireplace( 'www.', '', parse_url( home_url(), PHP_URL_HOST ) );
$file_host = str_ireplace( 'www.', '', parse_url( $url, PHP_URL_HOST ) );

// Return nothing if there aren't any $url parts or if the current host and $url host do not match
if ( ! isset( $parsed_url[1] ) || empty( $parsed_url[1] ) || ( $this_host != $file_host ) ) {
return;
}

// Now we're going to quickly search the DB for any attachment GUID with a partial path match
// Example: /uploads/2013/05/test-image.jpg
global $wpdb;

$attachment = $wpdb-&gt;get_col( $wpdb-&gt;prepare( "SELECT ID FROM {$wpdb-&gt;prefix}posts WHERE guid RLIKE %s;", $parsed_url[1] ) );

// Returns null if no attachment is found
return $attachment[0];
}
?>

 

¡Comparte!

Facebook
Twitter
WhatsApp
LinkedIn

Enseño como usar herramientas digitales y los trucos para generar ingresos online.

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

Post Recientes

¿Necesitas generar ventas?

Hey!, soy Xuxan Vigo y llevo años ayudando a los negocios a crecer, actualmente busco compartir todo lo que tengo este conocimiento.

Olvidate del SPAM, se te enviará lo prometido. Las actualizaciones de mi web en artículos, seminarios, plantillas y más.

¿Listo para aprender, emprender y mas?

Recibe solo contenido Interesante al unirte a mi gran comunidad:

Artículos de Marketing Digital

Atento a las próximas videoconferencias

Plantillas para planificar tus estrategias

No te lo pierdas

Déjanos tus datos!

Olvidate del SPAM, se te enviará lo prometido. Las actualizaciones de mi web en artículos, seminarios, plantillas y más.