Created
October 10, 2019 15:55
-
-
Save nikitasinelnikov/aa4430e9ebb9e737323207fd488597d6 to your computer and use it in GitHub Desktop.
Add srcset attribute to Cover Image, based on generated sizes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
add_filter( 'um_user_cover_photo_html__filter', 'um_cover_image_add_srcset' ); | |
function um_cover_image_add_srcset( $cover_html, $cover_uri, $alt, $is_default, $attrs ) { | |
$cover_min_width = UM()->options()->get( 'cover_min_width' ); | |
$base_dir = realpath( UM()->uploader()->get_upload_base_dir() ) . DIRECTORY_SEPARATOR; | |
$base_url = UM()->uploader()->get_upload_base_url(); | |
//multisite fix for old customers | |
if ( is_multisite() ) { | |
$multisite_fix_dir = str_replace( DIRECTORY_SEPARATOR . 'sites' . DIRECTORY_SEPARATOR . get_current_blog_id() . DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, $base_dir ); | |
if ( is_dir( $multisite_fix_dir ) ) { | |
$base_dir = realpath( $multisite_fix_dir ) . DIRECTORY_SEPARATOR; | |
$base_url = str_replace( '/sites/' . get_current_blog_id() . '/', '/', $base_url ); | |
} | |
} | |
$user_base_dir = $base_dir . um_user( 'ID' ) . DIRECTORY_SEPARATOR; | |
$user_base_url = $base_url . um_user( 'ID' ) . '/'; | |
$images = array(); | |
$matchs = array(); | |
$files = glob( $user_base_dir . 'cover_photo*', GLOB_BRACE ); | |
foreach ( $files as $file ) { | |
$filename = basename( $file ); | |
preg_match( '/cover_photo\-?(\d+)/', $filename, $matchs ); | |
$width = isset( $matchs[1] ) ? $matchs[1] : $cover_min_width; | |
$images[$width] = "{$user_base_url}{$filename} {$width}w"; | |
} | |
ksort( $images ); | |
$srcset = apply_filters( 'um_user_cover_photo_srcset__filter', implode( ', ', array_unique( $images ) ), um_user( 'ID' ), $files ); | |
$srcset_attr = ! empty( $srcset ) ? ' srcset="' . esc_attr( $srcset ) . '"' : ''; | |
$cover_html = $cover_uri ? '<img ' . $srcset_attr . ' src="' . esc_attr( $cover_uri ) . '" alt="' . esc_attr( $alt ) . '" />' : ''; | |
return $cover_html; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment