# attachment_url_to_postid()

URL: https://chugunov.pro/api-wordpress/functions/attachment_url_to_postid/
Проверено на WordPress 6.9, обновлено 06.08.2026.
Источник: независимый русскоязычный справочник chugunov.pro. Не является официальной документацией WordPress.

Тип: функция.
Появился в версии: 4.0.0.

## Сигнатура

```php
attachment_url_to_postid( string $url ): int
```

## Описание

Пытается преобразовать URL вложения в идентификатор записи.

## Параметры

- `$url` `string` — обязательный. URL для разрешения.

## Возвращаемое значение

`int`

## Исходный код

Файл: `wp-includes/media.php:5499`

```php
function attachment_url_to_postid( $url ) {
	global $wpdb;

	/**
	 * Filters the attachment ID to allow short-circuit the function.
	 *
	 * Allows plugins to short-circuit attachment ID lookups. Plugins making
	 * use of this function should return:
	 *
	 * - 0 (integer) to indicate the attachment is not found,
	 * - attachment ID (integer) to indicate the attachment ID found,
	 * - null to indicate WordPress should proceed with the lookup.
	 *
	 * Warning: The post ID may be null or zero, both of which cast to a
	 * boolean false. For information about casting to booleans see the
	 * PHP documentation.
	 * Use the === operator for testing the post ID when developing filters using
	 * this hook.
	 *
	 * @since 6.7.0
	 *
	 * @param int|null $post_id The result of the post ID lookup. Null to indicate
	 *                          no lookup has been attempted. Default null.
	 * @param string   $url     The URL being looked up.
	 */
	$post_id = apply_filters( 'pre_attachment_url_to_postid', null, $url );
	if ( null !== $post_id ) {
		return (int) $post_id;
	}

	$dir  = wp_get_upload_dir();
	$path = $url;

	$site_url   = parse_url( $dir['url'] );
	$image_path = parse_url( $path );

	// Force the protocols to match if needed.
	if ( isset( $image_path['scheme'] ) && ( $image_path['scheme'] !== $site_url['scheme'] ) ) {
		$path = str_replace( $image_path['scheme'], $site_url['scheme'], $path );
	}

	if ( str_starts_with( $path, $dir['baseurl'] . '/' ) ) {
		$path = substr( $path, strlen( $dir['baseurl'] . '/' ) );
	}

	$sql = $wpdb->prepare(
		"SELECT post_id, meta_value FROM $wpdb->postmeta WHERE meta_key = '_wp_attached_file' AND meta_value = %s",
		$path
	);

	$results = $wpdb->get_results( $sql );
	$post_id = null;

	if ( $results ) {
		// Use the first available result, but prefer a case-sensitive match, if exists.
		$post_id = reset( $results )->post_id;

		if ( count( $results ) > 1 ) {
			foreach ( $results as $result ) {
				if ( $path === $result->meta_value ) {
					$post_id = $result->post_id;
					break;
				}
			}
		}
	}

	/**
	 * Filters an attachment ID found by URL.
	 *
	 * @since 4.2.0
	 *
	 * @param int|null $post_id The post_id (if any) found by the function.
	 * @param string   $url     The URL being looked up.
	 */
	return (int) apply_filters( 'attachment_url_to_postid', $post_id, $url );
}
```

## История изменений

- 4.0.0 — Introduced.

## Связанные

Использует: [`wp_get_upload_dir`](https://chugunov.pro/api-wordpress/functions/wp_get_upload_dir/), [`apply_filters`](https://chugunov.pro/api-wordpress/functions/apply_filters/), `wpdb::get_results`, `wpdb::prepare`.
Используется в: [`wp_ajax_set_attachment_thumbnail`](https://chugunov.pro/api-wordpress/functions/wp_ajax_set_attachment_thumbnail/), `WP_Customize_Upload_Control::to_json`.

Оригинал в официальной документации: https://developer.wordpress.org/reference/functions/attachment_url_to_postid/
