How To Get Attachment URL By Post Id In WordPress

How To Get Attachment URL By Post Id In WordPress

Sometimes WordPress doesn’t deliver all the functionality we need, so there are WordPress PHP functions to help us, and luckily there are built-in WordPress PHP functions to get attachment URL by post id.

To get the attachment URL for a Post in WordPress, you can do this via the post id. You need to use the WordPress PHP function get_the_post_thumbnail($post_id); – This will return the entire image tag of the featured image from the post id you add.

Now there is another way to get the attachment URL by using the attachment id. This can be achieved by using wp_get_attachment_url(), let’s dive into it.

How To Get Attachment URL By Post Id In WordPress

This is applicable when you’re working with the PHP code itself. If your intention is otherwise, then don’t proceed with this guide. However, let’s dive into how we do it with a simple line of code in WordPress.

Usually, you would add this code to the function you’re building in your theme’s functions.php file. And to get the attachment URL via the post id, there is a built-in PHP function you can use where you add the post id as your parameter. It looks like this:

get_the_post_thumbnail_url($post_id, 'thumbnail');

The second parameter is the size you want the image to be at the URL you’re getting returned. So this function will return the URL of the featured image for the post id you enter as a parameter.

There is another way if your function is executing on the post itself where the attachment is present. This you can achieve by using the following line of code, again very simple:

wp_get_attachment_url(get_post_thumbnail_id(get_the_ID()));

The function get_the_ID() refers to the ID of the current page you’re on in WordPress, which in this case would be your blog post or a page.

[cboxarea id=”cbox-DZ7YzH84qT48YAf1″]

How To Get Attachment URL By Attachment Id In WordPress

Secondly, another option is to get the attachment URL when you have the attachment id. Moving forward, I’m assuming you have the attachment id. Otherwise, you can find that by clicking edit in your media library and in the URL, the ID will be.

But again, in your functions.php, where you’re building your PHP function, you need to add a simple line of PHP code. Because WordPress has been so kind to us to make another built-in function to achieve this. So the line of code looks like this:

wp_get_attachment_url($attachment_id);

Like the previous function, this will return the URL of your attachment id and nothing else. If it can’t find the attachment you’re requesting, it will simply return false.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *