Huy Hòa
  • Home
  • Code Learn
    • WordPress
    • Woocommerce
    • Joomla
    • PHP
    • SEO – Marketing
  • Vietnam
  • Healthcare
    • Womens Health
  • Beauty
  • Lifehack
  • Free Tools
    • Dog Pregnancy Calculator
    • BMI Calculator
    • Upside Down Text
    • Vietnamese Calendar
    • Vietnamese Typing
  • Contact Us
Nổi bật
  • The effects of cycling on the glutes
  • How to Get Rid of Hip Dips: A Complete Guide
  • The Importance of Waist Beads in Love Making
  • Tet Trung Thu: The Mid-Autumn Festival of Legends and Traditions
  • Discovering the Secrets of the Vietnamese Zodiac: Your Guide to the 12 Animal Signs
Friday, June 2
Huy Hòa
  • Home
  • Code Learn
    • WordPress
    • Woocommerce
    • Joomla
    • PHP
    • SEO – Marketing
  • Vietnam
  • Healthcare
    • Womens Health
  • Beauty
  • Lifehack
  • Free Tools
    • Dog Pregnancy Calculator
    • BMI Calculator
    • Upside Down Text
    • Vietnamese Calendar
    • Vietnamese Typing
  • Contact Us
Huy Hòa
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

  • 1 Source:
  • 2 Usage:
    • 2.1 Parameters
  • 3 Example:

Source:

File: wp-includes/media.php

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:

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:

$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:

$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

$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.

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

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

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

 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:

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;
}

4.7/5 - (996 votes)
References:

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

Master WP Cron: A Comprehensive Guide to Scheduling, Troubleshooting, and Optimization

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

Leave A Reply Cancel Reply

Search
Wordpress Themes & Plugins

PHP foreach: Tutorials and Examples

The PHP foreach statement executes the command in an array or an object. Foreach loop in the array or object it will execute the statement…

woocommerce_form_field() user guide and 10 sample examples

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

30+ Useful Custom WooCommerce Functions for Your WordPress Site

Optimize performance and security for WordPress using .htaccess

The 41+ best free and premium WooCommerce themes

How to get post data in WordPress?

Trending

Review of 20+ Best Primers for Mature Skin According to Makeup Experts

Primers that are best for mature skin will not only make your makeup last longer but will also prevent the foundation from getting smudged or…

Best 14 Leg Workouts And Exercises For Men And Women

Ly Thuong Kiet Street – The Way Associated Hero of Thang Long – Hanoi

List of the latest landline phone area codes in Vietnam

30+ Useful Custom WooCommerce Functions for Your WordPress Site

Traditional Vietnamese Food on Tet

Largest supermarket chain & 10 biggest supermarkets in Vietnam

Early signs and symptoms of lung cancer

4 Day Push-Pull Workout Routine for Mass and Strength

What are the best foods to get a bigger Butt?

Ngo Mon Gate – The beautiful of Hue citadel

The Best Exercises to Superset with the Bench Press

Quan Chuong city gate – a beauty of Hanoi 1000 years old

Exercising on Empty Stomach, good or bad?

Self-Reflection 101: How to Cleanse Your Soul and Improve Your Mental Health

Latest Post

The effects of cycling on the glutes

How to Get Rid of Hip Dips: A Complete Guide

The Importance of Waist Beads in Love Making

Tet Trung Thu: The Mid-Autumn Festival of Legends and Traditions

Discovering the Secrets of the Vietnamese Zodiac: Your Guide to the 12 Animal Signs

What is the Buddhist calendar?

Laugh Out Loud: The Best Funny Questions and Riddles You’ll Ever Read

Everything You Need to Know About Estrus and Mating in Dogs

Xuan Lien Nature Reserve: Protecting Vietnam’s Biodiversity and Ecosystems

Glute-Building Exercises for Beginners

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

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