Using WordPress ‘attachment_url_to_postid’ PHP filter

The attachment_url_to_postid WordPress PHP filter is used to modify an attachment ID found by its URL.

Usage

add_filter('attachment_url_to_postid', 'my_custom_function', 10, 2);
function my_custom_function($post_id, $url) {
  // your custom code here
  return $post_id;
}

Parameters

  • $post_id (int|null): The post_id (if any) found by the function.
  • $url (string): The URL being looked up.

More information

See WordPress Developer Resources: attachment_url_to_postid

Examples

Modify the attachment ID

Modify the attachment ID before it’s returned by the function:

add_filter('attachment_url_to_postid', 'modify_attachment_id', 10, 2);
function modify_attachment_id($post_id, $url) {
  // Modify the attachment ID, e.g., increment it by 1
  $post_id = $post_id + 1;
  return $post_id;
}

Log attachment URL lookups

Log attachment URL lookups for debugging purposes:

add_filter('attachment_url_to_postid', 'log_attachment_url_lookup', 10, 2);
function log_attachment_url_lookup($post_id, $url) {
  // Log the URL and the corresponding post_id
  error_log("Attachment URL: {$url}, Post ID: {$post_id}");
  return $post_id;
}

Remove attachment ID for specific URL pattern

Remove attachment ID for a specific URL pattern (e.g., external images):

add_filter('attachment_url_to_postid', 'remove_external_image_id', 10, 2);
function remove_external_image_id($post_id, $url) {
  // If the URL contains "external-images", remove the attachment ID
  if (strpos($url, 'external-images') !== false) {
    $post_id = null;
  }
  return $post_id;
}

Replace attachment ID for a specific domain

Replace attachment ID with a custom value for a specific domain:

add_filter('attachment_url_to_postid', 'replace_domain_attachment_id', 10, 2);
function replace_domain_attachment_id($post_id, $url) {
  // If the URL contains "example.com", replace the attachment ID with a custom value
  if (strpos($url, 'example.com') !== false) {
    $post_id = 12345;
  }
  return $post_id;
}

Add a prefix to the attachment ID

Add a custom prefix to the attachment ID:

add_filter('attachment_url_to_postid', 'prefix_attachment_id', 10, 2);
function prefix_attachment_id($post_id, $url) {
  // Add a custom prefix to the attachment ID
  $post_id = 'prefix_' . $post_id;
  return $post_id;
}