attachment_url_to_postid( string $url ): int

Tries to convert an attachment URL into a post ID.

Parameters

$urlstringrequired
The URL to resolve.

Return

int The found post ID, or 0 on failure.

Source

}

/**
 * Checks a specified post's content for gallery and, if present, return the first
 *
 * @since 3.6.0
 *
 * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
 * @param bool        $html Optional. Whether to return HTML or data. Default is true.
 * @return string|array Gallery data and srcs parsed from the expanded shortcode.
 */
function get_post_gallery( $post = 0, $html = true ) {
	$galleries = get_post_galleries( $post, $html );
	$gallery   = reset( $galleries );

	/**
	 * Filters the first-found post gallery.
	 *
	 * @since 3.6.0
	 *
	 * @param array       $gallery   The first-found post gallery.
	 * @param int|WP_Post $post      Post ID or object.
	 * @param array       $galleries Associative array of all found post galleries.
	 */
	return apply_filters( 'get_post_gallery', $gallery, $post, $galleries );
}

/**
 * Retrieves the image srcs from galleries from a post's content, if present.
 *
 * @since 3.6.0
 *
 * @see get_post_galleries()
 *
 * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global `$post`.
 * @return array A list of lists, each containing image srcs parsed.
 *               from an expanded shortcode
 */
function get_post_galleries_images( $post = 0 ) {
	$galleries = get_post_galleries( $post, false );
	return wp_list_pluck( $galleries, 'src' );
}

/**
 * Checks a post's content for galleries and return the image srcs for the first found gallery.
 *
 * @since 3.6.0
 *
 * @see get_post_gallery()
 *

Changelog

VersionDescription
4.0.0Introduced.

User Contributed Notes

  1. Skip to note 4 content

    Applying WordPress coding standards and best practices, example should look like this, Muhibul.

    $attachment_url     = 'https://example.com/wp-content/uploads/2023/09/image.jpg';
    $attachment_post_id = attachment_url_to_postid( esc_url( $attachment_url ) );
    
    if ( 0 !== $attachment_post_id ) {
        // An attachment post or page was found.
        printf( esc_html__( 'Attachment is associated with post ID: %s', 'textdomain'),
            $attachment_post_id
        );
    } else {
        // No attachment post or page found for the URL.
        esc_html_e( 'No post or page found for the provided attachment URL.', 'textdomain');
    }

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