WordPress.org

Make WordPress Core

Changeset 35419


Ignore:
Timestamp:
10/28/2015 08:00:14 PM (6 years ago)
Author:
azaozz
Message:

Responsive images:

  • Check if wp_get_attachment_metadata() has returned an array to prevent errors when using SVGs.
  • Only add the srcset attribute if there will be a sizes attribute.
  • Better filter names.
  • Some more inline docs fixes.

Props jaspermdegroot.
See #34430.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/media.php

    r35412 r35419  
    812812        $attr = wp_parse_args( $attr, $default_attr );
    813813
    814         // Generate srcset and sizes if not already present.
     814        // Generate 'srcset' and 'sizes' if not already present.
    815815        if ( empty( $attr['srcset'] ) ) {
    816816            $image_meta = wp_get_attachment_metadata( $attachment_id );
    817             $size_array = array( absint( $width ), absint( $height ) );
    818             $sources = wp_calculate_image_srcset( $src, $size_array, $image_meta, $attachment_id );
    819 
    820             if ( count( $sources ) > 1 ) {
    821                 $attr['srcset'] = wp_image_srcset_attr( $sources, $size_array, $image_meta, $attachment_id );
    822 
    823                 if ( empty( $attr['sizes'] ) && ( $sizes = wp_get_attachment_image_sizes( $size_array, $image_meta, $attachment_id ) ) ) {
    824                     $attr['sizes'] = $sizes;
     817
     818            if ( is_array( $image_meta ) ) {
     819                $size_array = array( absint( $width ), absint( $height ) );
     820                $sources    = wp_calculate_image_srcset( $src, $size_array, $image_meta, $attachment_id );
     821                $sizes      = wp_get_attachment_image_sizes( $size_array, $image_meta, $attachment_id );
     822
     823                if ( count( $sources ) > 1 && ( $sizes || ! empty( $attr['sizes'] ) ) ) {
     824                    $attr['srcset'] = wp_image_srcset_attr( $sources, $size_array, $image_meta, $attachment_id );
     825
     826                    if ( empty( $attr['sizes'] ) ) {
     827                        $attr['sizes'] = $sizes;
     828                    }
    825829                }
    826830            }
     
    907911 * @param array|string $size          Image size. Accepts any valid image size, or an array of width and height
    908912 *                                    values in pixels (in that order). Default 'medium'.
    909  * @param array        $image_meta    Optional. The image meta data.
     913 * @param array        $image_meta    Optional. The image meta data as returned by 'wp_get_attachment_metadata()'.
    910914 * @return string|bool A 'srcset' value string or false.
    911915 */
     
    925929    );
    926930
    927     // Calculate the sources for the srcset.
     931    // Calculate the sources for the 'srcset'.
    928932    $sources = wp_calculate_image_srcset( $image_url, $size_array, $image_meta, $attachment_id );
    929933
    930     // Only return a srcset value if there is more than one source.
     934    // Only return a 'srcset' value if there is more than one source.
    931935    if ( count( $sources ) < 2 ) {
    932936        return false;
     
    938942
    939943/**
    940  * A helper function to concatenate and filter the srcset attribute value.
     944 * A helper function to concatenate and filter the 'srcset' attribute value.
    941945 *
    942946 * @since 4.4.0
    943947 *
    944  * @param array   $sources       The array containing image sizes data as returned by wp_calculate_image_srcset().
     948 * @param array   $sources       The array containing image sizes data as returned by 'wp_calculate_image_srcset()'.
    945949 * @param array   $size_array    Array of width and height values in pixels (in that order).
    946  * @param array   $image_meta    The image meta data.
    947  * @param int     $attachment_id The image attachment post id to pass to the filter.
    948  * @return string The srcset attribute value.
     950 * @param array   $image_meta    The image meta data as returned by 'wp_get_attachment_metadata()'.
     951 * @param int     $attachment_id The image attachment ID to pass to the filter.
     952 * @return string The 'srcset' attribute value.
    949953 */
    950954function wp_image_srcset_attr( $sources, $size_array, $image_meta, $attachment_id ) {
     
    956960
    957961    /**
    958      * Filter the output of wp_get_attachment_image_srcset().
     962     * Filter the output of 'wp_image_srcset_attr()'.
    959963     *
    960964     * @since 4.4.0
    961965     *
    962      * @param string       $srcset        A source set formatted for a `srcset` attribute.
     966     * @param string       $srcset        A source set formatted for a 'srcset' attribute.
    963967     * @param int          $attachment_id Image attachment ID.
    964      * @param array|string $size          Image size. Accepts any valid image size, or an array of width and height
    965      *                                    values in pixels (in that order). Default 'medium'.
    966      * @param array        $image_meta    The image meta data.
    967      */
    968     return apply_filters( 'wp_get_attachment_image_srcset', rtrim( $srcset, ', ' ), $attachment_id, $size_array, $image_meta );
    969 }
    970 
    971 /**
    972  * A helper function to caclulate the image sources to include in a srcset attribute.
     968     * @param array|string $size          Image size. Image size name, or an array of width and height
     969     *                                    values in pixels (in that order).
     970     * @param array        $image_meta    The image meta data as returned by 'wp_get_attachment_metadata()'.
     971     */
     972    return apply_filters( 'wp_image_srcset', rtrim( $srcset, ', ' ), $attachment_id, $size_array, $image_meta );
     973}
     974
     975/**
     976 * A helper function to calculate the image sources to include in a 'srcset' attribute.
    973977 *
    974978 * @since 4.4.0
    975979 *
    976  * @param string $image_name    The file name, path, URL or partial path or URL of the image being matched.
     980 * @param string $image_name    The file name, path, URL, or partial path or URL, of the image being matched.
    977981 * @param array  $size_array    Array of width and height values in pixels (in that order).
    978  * @param array  $image_meta    The image meta data.
    979  * @param int    $attachment_id Optional. The image attachment post id to pass to the filter.
     982 * @param array  $image_meta    The image meta data as returned by 'wp_get_attachment_metadata()'.
     983 * @param int    $attachment_id Optional. The image attachment ID to pass to the filter.
    980984 * @return array|bool $sources {
    981985 *     Array image candidate values containing a URL, descriptor type, and
     
    984988 *     @type array $values {
    985989 *        @type string $url        An image URL.
    986  *        @type string $descriptor A width or density descriptor used in a srcset.
     990 *        @type string $descriptor A width or density descriptor used in a 'srcset'.
    987991 *        @type int    $value      The descriptor value representing a width or
    988992 *                                 or pixel density.
    989993 *     }
    990994 * }
    991  *
    992995 */
    993996function wp_calculate_image_srcset( $image_name, $size_array, $image_meta, $attachment_id = 0 ) {
     
    9981001    $image_sizes = $image_meta['sizes'];
    9991002
    1000     // Get the height and width for the image.
     1003    // Get the width and height of the image.
    10011004    $image_width = (int) $size_array[0];
    10021005    $image_height = (int) $size_array[1];
     
    10071010    }
    10081011
    1009     // Add full size to the img_sizes array.
     1012    // Add full size to the '$img_sizes' array.
    10101013    $image_sizes['full'] = array(
    10111014        'width'  => $image_meta['width'],
     
    10321035
    10331036    /**
    1034      * Filter the maximum width included in a 'srcset' attribute.
     1037     * Filter the maximum image width to be included in a 'srcset' attribute.
    10351038     *
    10361039     * @since 4.4.0
    10371040     *
    1038      * @param int          $max_width  The maximum width to include in the 'srcset'. Default '1600'.
    1039      * @param array|string $size_array Array of width and height values in pixels (in that order).
    1040      */
    1041     $max_srcset_width = apply_filters( 'max_srcset_image_width', 1600, $size_array );
     1041     * @param int   $max_width  The maximum image width to be included in the 'srcset'. Default '1600'.
     1042     * @param array $size_array Array of width and height values in pixels (in that order).
     1043     */
     1044    $max_srcset_image_width = apply_filters( 'max_srcset_image_width', 1600, $size_array );
    10421045
    10431046    // Array to hold URL candidates.
     
    10551058        }
    10561059
    1057         // Filter out images that are wider than $max_srcset_width.
    1058         if ( $max_srcset_width && $image['width'] > $max_srcset_width ) {
     1060        // Filter out images that are wider than '$max_srcset_image_width'.
     1061        if ( $max_srcset_image_width && $image['width'] > $max_srcset_image_width ) {
    10591062            continue;
    10601063        }
     
    10811084
    10821085    /**
    1083      * Filter the output of wp_get_attachment_image_srcset_array().
     1086     * Filter the output of 'wp_calculate_image_srcset()'.
    10841087     *
    10851088     * @since 4.4.0
    10861089     *
    10871090     * @param array        $sources       An array of image URLs and widths.
    1088      * @param int          $attachment_id Attachment ID for image.
    1089      * @param array|string $size          Image size. Accepts any valid image size, or an array of width and height
    1090      *                                    values in pixels (in that order). Default 'medium'.
    1091      * @param array        $image_meta    The image meta data.
    1092 
    1093      */
    1094     return apply_filters( 'wp_get_attachment_image_srcset_array', array_values( $sources ), $attachment_id, $size_array, $image_meta );
    1095 }
    1096 
    1097 /**
    1098  * Create `sizes` attribute value for an image.
     1091     * @param int          $attachment_id Image attachment ID.
     1092     * @param array|string $size          Image size. Image size name, or an array of width and height
     1093     *                                    values in pixels (in that order).
     1094     * @param array        $image_meta    The image meta data as returned by 'wp_get_attachment_metadata()'.
     1095
     1096     */
     1097    return apply_filters( 'wp_calculate_image_srcset', array_values( $sources ), $attachment_id, $size_array, $image_meta );
     1098}
     1099
     1100/**
     1101 * Create 'sizes' attribute value for an image.
    10991102 *
    11001103 * @since 4.4.0
    11011104 *
    1102  * @param array|string $size          Image size. Accepts any valid image size name (thumbnail, medium, etc.),
     1105 * @param array|string $size          Image size. Accepts any valid image size name ('thumbnail', 'medium', etc.),
    11031106 *                                    or an array of width and height values in pixels (in that order).
    1104  * @param array        $image_meta    Optional. The image meta data.
    1105  * @param int          $attachment_id Optional. Image attachment ID. Either $image_meta or $attachment_id is needed
    1106  *                                    when using image size name.
     1107 * @param array        $image_meta    Optional. The image meta data as returned by 'wp_get_attachment_metadata()'.
     1108 * @param int          $attachment_id Optional. Image attachment ID. Either `$image_meta` or `$attachment_id` is needed
     1109 *                                    when using the image size name as argument for `$size`.
    11071110 *
    11081111 * @return string|bool A valid source size value for use in a 'sizes' attribute or false.
     
    11201123        }
    11211124
    1122         if ( $image_meta ) {
     1125        if ( is_array( $image_meta ) ) {
    11231126            $width = _wp_get_image_size_from_meta( $size, $image_meta );
    11241127            if ( $width ) {
    1125                 $width = $width[0];
     1128                $width = absint( $width[0] );
    11261129            }
    11271130        }
     
    11321135    }
    11331136
    1134     // Setup the default sizes attribute.
    1135     $sizes = sprintf( '(max-width: %1$dpx) 100vw, %1$dpx', (int) $width );
    1136 
    1137     /**
    1138      * Filter the output of wp_get_attachment_image_sizes().
     1137    // Setup the default 'sizes' attribute.
     1138    $sizes = sprintf( '(max-width: %1$dpx) 100vw, %1$dpx', $width );
     1139
     1140    /**
     1141     * Filter the output of 'wp_get_attachment_image_sizes()'.
    11391142     *
    11401143     * @since 4.4.0
    11411144     *
    11421145     * @param string       $sizes         A source size value for use in a 'sizes' attribute.
    1143      * @param array|string $size          Image size. Accepts any valid image size, or an array of width and height
    1144      *                                    values in pixels (in that order). Default 'medium'.
    1145      * @param array        $image_meta    The image meta data.
    1146      * @param int          $attachment_id Post ID of the original image.
     1146     * @param array|string $size          Image size. Image size name, or an array of width and height
     1147     *                                    values in pixels (in that order).
     1148     * @param array        $image_meta    The image meta data as returned by 'wp_get_attachment_metadata()'.
     1149     * @param int          $attachment_id Image attachment ID of the original image.
    11471150     */
    11481151    return apply_filters( 'wp_get_attachment_image_sizes', $sizes, $size, $image_meta, $attachment_id );
     
    11541157 * @since 4.4.0
    11551158 *
    1156  * @see wp_image_add_srcset_and_sizes()
     1159 * @see 'wp_image_add_srcset_and_sizes()'
    11571160 *
    11581161 * @param string $content The raw post content to be filtered.
     
    11681171            ( $attachment_id = absint( $class_id[1] ) ) ) {
    11691172
    1170             // If exactly the same image tag is used more than once, overwrite it.
    1171             // All identical tags will be replaced later with str_replace().
     1173            /*
     1174             * If exactly the same image tag is used more than once, overwrite it.
     1175             * All identical tags will be replaced later with 'str_replace()'.
     1176             */
    11721177            $selected_images[ $image ] = $attachment_id;
    11731178            // Overwrite the ID when the same image is included more than once.
     
    11781183    if ( count( $attachment_ids ) > 1 ) {
    11791184        /*
    1180          * Warm object cache for use with get_post_meta().
     1185         * Warm object cache for use with 'get_post_meta()'.
    11811186         *
    11821187         * To avoid making a database call for each image, a single query
     
    11991204 * @since 4.4.0
    12001205 *
    1201  * @see wp_get_attachment_image_srcset()
    1202  * @see wp_get_attachment_image_sizes()
     1206 * @see 'wp_get_attachment_image_srcset()'
     1207 * @see 'wp_get_attachment_image_sizes()'
    12031208 *
    12041209 * @param string $image         An HTML 'img' element to be filtered.
    1205  * @param array  $image_meta    The image meta data.
     1210 * @param array  $image_meta    The image meta data as returned by 'wp_get_attachment_metadata()'.
    12061211 * @param int    $attachment_id Image attachment ID.
    1207  * @return string Converted 'img' element with `srcset` and `sizes` attributes added.
     1212 * @return string Converted 'img' element with 'srcset' and 'sizes' attributes added.
    12081213 */
    12091214function wp_image_add_srcset_and_sizes( $image, $image_meta, $attachment_id ) {
    1210     // Ensure the image meta exists
     1215    // Ensure the image meta exists.
    12111216    if ( empty( $image_meta['sizes'] ) ) {
    12121217        return $image;
     
    12161221    list( $src ) = explode( '?', $src );
    12171222
    1218     // Return early if we coudn't get the image source.
     1223    // Return early if we couldn't get the image source.
    12191224    if ( ! $src ) {
    12201225        return $image;
    12211226    }
    12221227
    1223     // Bail early when an image has been inserted and later edited.
     1228    // Bail early if an image has been inserted and later edited.
    12241229    if ( preg_match( '/-e[0-9]{13}/', $image_meta['file'], $img_edit_hash ) &&
    12251230        strpos( wp_basename( $src ), $img_edit_hash[0] ) === false ) {
     
    12331238    if ( ! $width || ! $height ) {
    12341239        /*
    1235          * If attempts to parse the size value failed, attempt to use the image
    1236          * metadata to match the image file name from 'src' against the available sizes for an attachment.
     1240         * If attempts to parse the size value failed, attempt to use the image meta data to match
     1241         * the image file name from 'src' against the available sizes for an attachment.
    12371242         */
    12381243        $image_filename = wp_basename( $src );
     
    12601265
    12611266    $srcset = $sizes = '';
    1262     // Only calculate srcset and sizes values if there is more than one source.
     1267    // Only calculate 'srcset' and 'sizes' values if there is more than one source.
    12631268    if ( count( $sources ) > 1 ) {
    12641269        $srcset = wp_image_srcset_attr( $sources, $size_array, $image_meta, $attachment_id );
     
    12671272
    12681273    if ( $srcset && $sizes ) {
    1269         // Format the srcset and sizes string and escape attributes.
     1274        // Format the 'srcset' and 'sizes' string and escape attributes.
    12701275        $srcset_and_sizes = sprintf( ' srcset="%s" sizes="%s"', esc_attr( $srcset ), esc_attr( $sizes ) );
    12711276
    1272         // Add srcset and sizes attributes to the image markup.
     1277        // Add 'srcset' and 'sizes' attributes to the image markup.
    12731278        $image = preg_replace( '/<img ([^>]+?)[\/ ]*>/', '<img $1' . $srcset_and_sizes . ' />', $image );
    12741279    }
Note: See TracChangeset for help on using the changeset viewer.