Huy Hoa
  • Home
  • Code Learn
    • WordPress
    • Woocommerce
    • Joomla
    • PHP
    • SEO – Marketing
  • Vietnam
  • Healthcare
    • Womens Health
  • Beauty
  • Lifehack
  • Free Tools
    • BMI Calculator
    • Upside Down Text
    • Vietnamese Typing
  • Contact Us
Nổi bật
  • How do you treat an infected belly button piercing?
  • Seizures in Dogs: Causes, Symptoms, Types, and Treatments
  • Vietnamese symbols throughout 4000 years history
  • 4 Day Push-Pull Workout Routine for Mass and Strength
  • The Best Push Pull Legs Routine For Building Muscle and Strength
Tuesday, September 16
Huy Hoa
  • Home
  • Code Learn
    • WordPress
    • Woocommerce
    • Joomla
    • PHP
    • SEO – Marketing
  • Vietnam
  • Healthcare
    • Womens Health
  • Beauty
  • Lifehack
  • Free Tools
    • BMI Calculator
    • Upside Down Text
    • Vietnamese Typing
  • Contact Us
Huy Hoa
Home»WordPress»wp_get_attachment_image_src() – a WordPress Function to Returns Array of Image Data

wp_get_attachment_image_src() – a WordPress Function to Returns Array of Image Data

Facebook Twitter Pinterest LinkedIn Tumblr Email
wp_get_attachment_image_src() - a WordPress Function
wp_get_attachment_image_src() - a WordPress Function

wp_get_attachment_image_src() is a WordPress Function retrieve an image to represent an attachment. In practical use wp_get_attachment_image_src is very useful for displaying an attached image if you don’t need image meta or the alt attribute.

Table of Contents

Source:

File: wp-includes/media.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function wp_get_attachment_image_src( $attachment_id, $size = 'thumbnail', $icon = false ) {
    // Get a thumbnail or intermediate image if there is one.
    $image = image_downsize( $attachment_id, $size );
    if ( ! $image ) {
        $src = false;
        if ( $icon ) {
            $src = wp_mime_type_icon( $attachment_id );
            if ( $src ) {
                /** This filter is documented in wp-includes/post.php */
                $icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/media' );
                $src_file               = $icon_dir . '/' . wp_basename( $src );
                list( $width, $height ) = wp_getimagesize( $src_file );
            }
        }
        if ( $src && $width && $height ) {
            $image = array( $src, $width, $height, false );
        }
    }
   return apply_filters( 'wp_get_attachment_image_src', $image, $attachment_id, $size, $icon );
}

Usage:

1
wp_get_attachment_image_src( $attachment_id = 18 );

Parameters

$attachment_id (int) (Required) Image attachment ID.
$size (string|int[]) (Optional) Image size. Accepts any registered image size name, or an array of width and height values in pixels (in that order). Default value: ‘thumbnail’
$icon (bool) (Optional) Whether the image should fall back to a mime type icon. Default value: false.

By default, wp_get_attachment_image_src return an array of image with 4 values url, width, height, is_intermediateIf there is no image, the function returns false.

Example:

Get URL, width, the height of image with attachment id 18:

1
2
3
4
$img_attributes = wp_get_attachment_image_src( $attachment_id = 18 );
if ( $img_attributes ) : ?>
    <img src="<?php echo $img_attributes[0]; ?>" width="<?php echo $img_attributes[1]; ?>" height="<?php echo $img_attributes[2]; ?>" />
<?php endif; ?>

To get the original size URL of an image in the function wp_get_attachment_image_src use:

1
2
$img_atts = wp_get_attachment_image_src(18, 'full'); // 18 is ID of attachment, NOT post ID
<img src="<?php echo $img_atts[0]; ?>"

Size option:  If you want to get the URL of an attachment in custom size, you can declare $size according to array(width, height)

The example below used wp_get_attachment_image_src to takes the thumbnail size image and the custom size is 640x400

1
2
3
4
5
6
$thumbnail_url_custom = wp_get_attachment_image_src(get_post_thumbnail_id($post_id), array('640','400'), true ); // Custom size 640x400
$thumbnail_url_thumb = wp_get_attachment_image_src(get_post_thumbnail_id($post_id), 'thumbnail', true ); // Thumbnail size
 
$thumbnail_url_thumb = $thumbnail_url_thumb[0]; // Somthing like: https://huyhoa.net/wp-content/uploads/2021/07/how-to-get-post-id-150x150.jpg
 
$thumbnail_url_custom = $thumbnail_url_custom[0];  // Somthing like: https://huyhoa.net/wp-content/uploads/2021/07/how-to-get-post-id-640x400.jpg

Please note that if the thumbnail size 640×400 does not exist, wp_get_attachment_image_src will not working and return false.

In some cases, the array $size will not working in wp_get_attachment_image_src function. The reason is that $size does not exist, so you have to add that $size support by use adds image size function in your functions.php file like this.

1
2
3
4
5
add_action( 'after_setup_theme', 'huyhoa_theme_setup' );
function huyhoa_theme_setup() {
    add_image_size( 'category-thumb', 180 ); // 300 pixels wide (and unlimited height)
    add_image_size( 'homepage-thumb', 120, 120, true ); // (cropped to 120px x 120px)
}

Then you can use this code to get the image URL with the defined size

1
wp_get_attachment_image_src( $thumbnail_id, 'category-thumb', '', true );

Another example of getting the attachment URL for the medium-sized image

1
wp_get_attachment_image_src( $thumbnail_id, 'medium')[0];

Alt text: wp_get_attachment_image_src function will not return an image attachment’s Alt text. If you want to get alt text, you should use wp_get_attachment_image() a function instead.

Bonus: In case you want to get an attachment ID from an image URL, please use this function:

1
2
3
4
5
6
7
8
9
10
11
12
function get_attachment_id_from_src ($src) {
    global $wpdb;
    $reg = "/-[0-9]+x[0-9]+?.(jpg|jpeg|png|gif)$/i";
    $src1 = preg_replace($reg,'',$src);
    if($src1 != $src){
    $ext = pathinfo($src, PATHINFO_EXTENSION);
    $src = $src1 . '.' .$ext;
}
$query = "SELECT ID FROM {$wpdb->posts} WHERE guid='$src'";
$id = $wpdb->get_var($query);
return $id;
}

Wordpress
Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
Previous ArticleCancer Causes, Types, Symptoms, and Treatments
Next Article How to Lose Fat Without Losing Muscle: 7 Tried-and-True Methods
Huy Hoa
  • Website

Related Posts

The 41+ best free and premium WooCommerce themes

30+ Useful Custom WooCommerce Functions for Your WordPress Site

Optimize performance and security for WordPress using .htaccess

How to get post data in WordPress?

woocommerce_form_field() user guide and 10 sample examples

5 examples of getting Post by ID & 11 Ways to Get Post ID in WordPress

These 70+ Specialized Blogs About WordPress Will Help Bloggers Succeed

How to Fix PhpMyAdmin Error Incorrect Format Parameter

PHP foreach: Tutorials and Examples

Leave A Reply Cancel Reply

Wordpress Themes & Plugins

How to Fix PhpMyAdmin Error Incorrect Format Parameter

PhpMyAdmin Error – incorrect format parameter might appear on multiple hosting platforms like shared hosting, VPS, localhost, or Dedicated Server. You may get incorrect format…

30+ Useful Custom WooCommerce Functions for Your WordPress Site

5 examples of getting Post by ID & 11 Ways to Get Post ID in WordPress

PHP foreach: Tutorials and Examples

How to get post data in WordPress?

wp_get_attachment_image_src() – a WordPress Function to Returns Array of Image Data

woocommerce_form_field() user guide and 10 sample examples

Trending

SEO Glossary of Terms: Definitions and Explanations

Search Engine Optimisation (SEO), or optimization in the USA, are the techniques used to help a website rank near the top, or best of all…

Rosehip Helps Reduce Development of Cancer Cells for ER+ Breast Cancer

Uoc Le Pork Pies – a Famous Ancient Trade Village in Hanoi

Waking up with headaches: 15 Possible Causes, Prevention, and Treatments

Challenge Yourself with Coconut Worms: Benefits and Negatives sides of coconut worm You Should Know

Does whey protein cause hair loss?

Vietnam Train: Tickets, Routes, Prices and Departure time

These 70+ Specialized Blogs About WordPress Will Help Bloggers Succeed

Usage of Opioids during Pregnancy put babies at risk of Neonatal Abstinence Syndrome

Hang Bac Street – Famous Silver and Gold Jewelry in Hanoi

Perfect Female Body – Ideal Body Measurements for Women

Can cats eat Seafood like fish, salmon, sardines or shrimp?

How to read allergy skin test results?

Vietnam welcomes tourists from 2022

Where Can You Smoke on a Cruise Ship?

Latest Post

How do you treat an infected belly button piercing?

Seizures in Dogs: Causes, Symptoms, Types, and Treatments

Vietnamese symbols throughout 4000 years history

4 Day Push-Pull Workout Routine for Mass and Strength

The Best Push Pull Legs Routine For Building Muscle and Strength

The 41+ best free and premium WooCommerce themes

Is it normal if you have a headache or temple pain after tooth extraction?

Can Dogs Eat Strawberries? Safety guide to avoid poisonous to dogs

Pain meds for dogs: what can I give my dog for pain relief?

Can dogs get headaches and how do you know?

© 2025 All Rights Reserved HuyHoa.Net. DMCA.com Protection Status .
Hosted by Dreamhost. Follow us on Follow Huy Hoa on Google News Google News.
  • About Us
  • Privacy Policy
  • Cookie Policy
  • Contact Us

Type above and press Enter to search. Press Esc to cancel.