Using WordPress ‘attachment_url_to_postid()’ PHP function

The attachment_url_to_postid() WordPress PHP function tries to convert an attachment URL into a post ID.

Usage

To use the attachment_url_to_postid() function, simply pass the URL of the attachment as a string. For instance:

$post_id = attachment_url_to_postid('http://example.com/wp-content/uploads/2023/05/image.jpg');

This will return the post ID, for example, 123.

Parameters

  • $url (string) – This is the URL of the attachment you wish to convert into a post ID.

More information

See WordPress Developer Resources: attachment_url_to_postid()

This function is widely used and is not depreciated. However, it may return 0 if the URL does not belong to any attachment in the WordPress media library.

Examples

Converting a URL to a Post ID

Here’s a basic use of the function. This will convert the given URL into a post ID.

$post_id = attachment_url_to_postid('http://example.com/wp-content/uploads/2023/05/image.jpg');
echo $post_id; // Outputs: 123

Checking if a URL Belongs to an Attachment

In this example, we’ll check if a URL belongs to an attachment in the WordPress media library.

$post_id = attachment_url_to_postid('http://example.com/wp-content/uploads/2023/05/image.jpg');

if($post_id > 0) {
    echo 'This URL belongs to an attachment!';
} else {
    echo 'This URL does not belong to an attachment.';
}

Retrieving Attachment Metadata

This example retrieves the attachment metadata using the post ID.

$post_id = attachment_url_to_postid('http://example.com/wp-content/uploads/2023/05/image.jpg');
$meta = wp_get_attachment_metadata($post_id);

print_r($meta); // Outputs the attachment metadata

Displaying the Attachment Image

Here, we’ll display the image using the returned post ID.

$post_id = attachment_url_to_postid('http://example.com/wp-content/uploads/2023/05/image.jpg');
echo wp_get_attachment_image($post_id, 'thumbnail');

Retrieving the Attachment Post

In this last example, we’ll retrieve the attachment post using the post ID.

$post_id = attachment_url_to_postid('http://example.com/wp-content/uploads/2023/05/image.jpg');
$post = get_post($post_id);

print_r($post); // Outputs the attachment post