string, 'width' => int, 'height' => int, * 'alt' => string ). Width and height are 0 when WordPress * has no size recorded for the file. */ public static function describe( $attachment_id ) { $attachment_id = absint( $attachment_id ); if ( ! self::is_usable_attachment( $attachment_id ) ) { return array(); } $source = wp_get_attachment_image_src( $attachment_id, self::pick_size( $attachment_id ) ); if ( ! is_array( $source ) || empty( $source[0] ) ) { return array(); } $width = isset( $source[1] ) ? (int) $source[1] : 0; $height = isset( $source[2] ) ? (int) $source[2] : 0; // Too small to be shown as a share image: let the caller fall back. if ( $width && $height && min( $width, $height ) < self::MIN_SIDE ) { return array(); } $alt = get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ); return array( 'url' => self::absolute_url( $source[0] ), 'width' => $width, 'height' => $height, 'alt' => DevLab_OG_Text::plain( $alt ), ); } /** * Whether an image is big enough for X's large summary card. * * @param array $image Result of describe(). * @return bool */ public static function fits_large_card( $image ) { return ! empty( $image['url'] ) && ! empty( $image['width'] ) && ! empty( $image['height'] ) && $image['width'] >= self::LARGE_CARD_WIDTH && $image['height'] >= self::LARGE_CARD_HEIGHT; } /** * Chooses which size of the attachment to use: the smallest one that is at * least TARGET_WIDTH wide and keeps the original proportions (so the * picture is not cropped), or the full size when there is none. This keeps * huge originals out of the tags, since X refuses files above 5 MB. * * @param int $attachment_id Attachment ID. * @return string Size name for wp_get_attachment_image_src(). */ private static function pick_size( $attachment_id ) { $meta = wp_get_attachment_metadata( $attachment_id ); if ( ! is_array( $meta ) || empty( $meta['sizes'] ) || ! is_array( $meta['sizes'] ) || empty( $meta['width'] ) || empty( $meta['height'] ) ) { return 'full'; } $best = 'full'; $best_width = (int) $meta['width']; foreach ( $meta['sizes'] as $name => $size ) { if ( empty( $size['width'] ) || empty( $size['height'] ) ) { continue; } $width = (int) $size['width']; if ( $width < self::TARGET_WIDTH || $width >= $best_width ) { continue; } if ( ! wp_image_matches_ratio( $width, (int) $size['height'], (int) $meta['width'], (int) $meta['height'] ) ) { continue; } $best = (string) $name; $best_width = $width; } return $best; } /** * Makes sure an image address is absolute, as the networks require. * * @param string $url Address from WordPress. * @return string */ private static function absolute_url( $url ) { $url = (string) $url; if ( 0 === strpos( $url, '//' ) ) { return set_url_scheme( $url ); } if ( 0 === strpos( $url, '/' ) ) { return home_url( $url ); } return $url; } }