0

I have been trying to fetch the URL of image attachments ( e.g. - http:// localhost/mytheme/post-format-gallery/100_5478.jpg ) using their attachment links ( e.g. - http:// localhost/mytheme/post-format-gallery/100_5478/). Is their a direct function to achieve this?

I also tried involving the attachment ID but was stuck there also as the only thing I have is an attachment link which is not much help.

I am looking to modify the markup of the gallery in WordPress in order to enable lightbox for it.

There is a hack where the extension is added at the end using JS but it is not at all reliable.

Any help would be greatly appreciated.

0

There's a couple functions to get different attachment parameters based on one another, but a cursory look doesn't indicate there's one to get one based on the Attachment Page URL.

You could try and get the Post ID based on the Name (or Title) using the $wpdb class, and then drop that ID into the wp_get_attachment_image_src() function. Something like this would get you started:

function get_attachment_id_by_url( $url ){
    global $wpdb;

    $url   = trim( $url, ' /' ); // Trim whitespace and trailing slash
    $parts = explode( '/', $url ); 
    $name  = end( $parts ); // We only want the last part

    if( ! $result = $wpdb->get_row( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_name = %s", $name ) ) ) // potentially replace post_name with post_title
        return false;

    return $result->ID;
}

This would let you do something like this:

// Attachment URL we want to utilize
$image_url = 'https://example.com/attachment/name_of_photo/';

// Get the ID using our function above
$image_id  = get_attachment_id_by_url( $image_url );

// Get the SRC parameters from that ID (use whatever `$size` args you want)
$image_src = wp_get_attachment_image_src( $image_url, 'full' );

/**
 * var_dump($image_src) Output:
 * 
 * array(4) {
 *    [0]=> string(48) "https://example.com/attachment/name_of_photo.png"
 *    [1]=> int(640)
 *    [2]=> int(480)
 *    [3]=> bool(true)
 * }
 */
  • Seems Legit! Gonna try this one! – Divjot Singh Oct 6 '18 at 7:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.