wp_media_personal_data_exporter( string $email_address, int $page = 1 ): array

In this article

Finds and exports attachments associated with an email address.

Parameters

$email_addressstringrequired
The attachment owner email address.
$pageintoptional
Attachment page number.

Default:1

Return

array An array of personal data.
  • data array[]
    An array of personal data arrays.
  • done bool
    Whether the exporter is finished.

Source

 */
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.
	 *
	 * @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;

Changelog

VersionDescription
4.9.6Introduced.

User Contributed Notes

You must log in before being able to contribute a note or feedback.