Home » Hooks » wp_get_attachment_url

The wp_get_attachment_url hook is used in WordPress to retrieve the URL for the given attachment. It is a filter hook that allows developers to modify the URL returned by WordPress for the attachment.

The function is called when you want to get the URL of an attachment that’s uploaded to WordPress. The default URL that WordPress generates for an attachment is based on the site’s settings, but by using this hook, developers can modify the URL in any way they want.

This hook is useful when you want to change the default URL for an attachment to something more descriptive or to change the URL based on certain conditions.

Example usage code:

function modify_attachment_url( $url, $post_id ) {
    // Get the post type of the attachment.
    $post_type = get_post_type( $post_id );

    // If it's an image attachment, add a custom parameter to the URL.
    if ( $post_type === 'attachment' ) {
        $url = add_query_arg( 'custom_parameter', 'true', $url );

    return $url;
add_filter( 'wp_get_attachment_url', 'modify_attachment_url', 10, 2 );

In this example, we’re using the wp_get_attachment_url filter hook to modify the URL for an image attachment. We’re checking if the post type of the attachment is ‘attachment’, and if it is, we’re adding a custom parameter to the URL. The modified URL is then returned and used by WordPress.

Learn More on WordPress.org

WordPress snippets using the wp_get_attachment_url hook

Register an account to save your snippets or go Pro to get more features.