Get attachment id by file path in WordPress

I know the path to the file and I like getting the attachment id.

There is a function that requires an identifier to get a URL, but I need it to be the opposite (although the path is not a URL) wp_get_attachment_url()

+11
source share
6 answers

I used this cool cut pippinsplugins.com

Add this function to the functions.php file

// retrieves the attachment ID from the file URL
function pippin_get_image_id($image_url) {
    global $wpdb;
    $attachment = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $image_url )); 
        return $attachment[0]; 
}

Then use this code on your page or template to store / print / use the identifier:

// set the image url
$image_url = 'http://yoursite.com/wp-content/uploads/2011/02/14/image_name.jpg';

// store the image ID in a var
$image_id = pippin_get_image_id($image_url);

// print the id
echo $image_id;

Original post here: https://pippinsplugins.com/retrieve-attachment-id-from-image-url/

Hope ti helps;) Francesco

+13
source

attachment_url_to_postid.

$rm_image_id = attachment_url_to_postid( 'http://example.com/wp-content/uploads/2016/05/castle-old.jpg' );
echo $rm_image_id;

+1

URL

URL- , .

: /uploads/2018/02/my-image-300x250.jpg vs /uploads/2018/02/my-image.jpg

WP Scholar . , URL.

, , , , .

/**
 * 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;
}

WP_Query , WP_Query , SQL- .

0

, , . , , " WordPress".

This function will support either the path or the URL, and uses the built-in WordPress attachment_url_to_postid function for proper final processing:

/**
 * Find the post ID for a file PATH or URL
 *
 * @param string $path
 *
 * @return int
 */
function find_post_id_from_path( $path ) {
    // detect if is a media resize, and strip resize portion of file name
    if ( preg_match( '/(-\d{1,4}x\d{1,4})\.(jpg|jpeg|png|gif)$/i', $path, $matches ) ) {
        $path = str_ireplace( $matches[1], '', $path );
    }

    // process and include the year / month folders so WP function below finds properly
    if ( preg_match( '/uploads\/(\d{1,4}\/)?(\d{1,2}\/)?(.+)$/i', $path, $matches ) ) {
        unset( $matches[0] );
        $path = implode( '', $matches );
    }

    // at this point, $path contains the year/month/file name (without resize info)

    // call WP native function to find post ID properly
    return attachment_url_to_postid( $path );
}
0
source

Based on the answer from @FrancescoCarlucci, I could make some improvements.

Sometimes, for example, when you edit an image in WordPress, it creates a copy from the original and adds the copy download path as a message meta (key _wp_attached_file) that is not respected in the response.

Here's a refined request that includes these changes:

function jfw_get_image_id($file_url) {
    $file_path = ltrim(str_replace(wp_upload_dir()['baseurl'], '', $file_url), '/');

    global $wpdb;
    $statement = $wpdb->prepare("SELECT `ID` FROM `wp_posts` AS posts JOIN `wp_postmeta` AS meta on meta.`post_id`=posts.`ID` WHERE posts.`guid`='%s' OR (meta.`meta_key`='_wp_attached_file' AND meta.`meta_value` LIKE '%%%s');",
        $file_url,
        $file_path);

    $attachment = $wpdb->get_col($statement);

    if (count($attachment) < 1) {
        return false;
    }

    return $attachment[0]; 
}
-1
source

All Articles