/** * Retrieves the value for an image attachment's 'srcset' attribute. * * @since 4.4.0 * * @param int $attachment_id Image attachment ID. * @param array|string $size Image size. Accepts any valid image size, or an array of width and height * values in pixels (in that order). Default 'medium'. * @return string|bool A 'srcset' value string or false. */ function wp_get_attachment_image_srcset($attachment_id, $size = 'medium') { $srcset_array = wp_get_attachment_image_srcset_array($attachment_id, $size); // Only return a srcset value if there is more than one source. if (count($srcset_array) <= 1) { return false; } $srcset = ''; foreach ($srcset_array as $source) { $srcset .= $source['url'] . ' ' . $source['value'] . $source['descriptor'] . ', '; } /** * Filter the output of wp_get_attachment_image_srcset(). * * @since 4.4.0 * * @param string $srcset A source set formated for a `srcset` attribute. * @param int $attachment_id Attachment ID for image. * @param array|string $size Image size. Accepts any valid image size, or an array of width and height * values in pixels (in that order). Default 'medium'. */ return apply_filters('wp_get_attachment_image_srcset', rtrim($srcset, ', '), $attachment_id, $size); }
/** * Retrieves the value for an image attachment's 'srcset' attribute. * * @since 4.4.0 * * @param int $attachment_id Image attachment ID. * @param string $size Optional. Name of image size. Default 'medium'. * @return string|bool A 'srcset' value string or false. */ function wp_get_attachment_image_srcset($attachment_id, $size = 'medium') { $srcset_array = wp_get_attachment_image_srcset_array($attachment_id, $size); // Only return a srcset value if there is more than one source. if (count($srcset_array) <= 1) { return false; } $srcset = ''; foreach ($srcset_array as $source) { $srcset .= $source['url'] . ' ' . $source['value'] . $source['descriptor'] . ', '; } /** * Filter the output of wp_get_attachment_image_srcset(). * * @since 4.4.0 * * @param string $srcset A source set formated for a `srcset` attribute. * @param int $attachment_id Attachment ID for image. * @param array|string $size Size of image, either array or string. */ return apply_filters('wp_get_attachment_image_srcset', rtrim($srcset, ', '), $attachment_id, $size); }
/** * @ticket 33641 */ function test_wp_get_attachment_image_srcset_array_no_width() { // Filter image_downsize() output. add_filter('wp_generate_attachment_metadata', array($this, '_test_wp_get_attachment_image_srcset_array_no_width_filter')); $old_meta = get_post_meta(self::$large_id, '_wp_attachment_metadata', true); $file = get_attached_file(self::$large_id); $data = wp_generate_attachment_metadata(self::$large_id, $file); wp_update_attachment_metadata(self::$large_id, $data); $srcset = wp_get_attachment_image_srcset_array(self::$large_id, 'medium'); update_post_meta(self::$large_id, '_wp_attachment_metadata', $old_meta); // The srcset should be false. $this->assertFalse($srcset); }