|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Wordlift\Widgets; |
|
4
|
|
|
/** |
|
5
|
|
|
* @since 3.28.0 |
|
6
|
|
|
* @author Naveen Muthusamy <[email protected]> |
|
7
|
|
|
*/ |
|
8
|
|
|
class Srcset_Util { |
|
9
|
|
|
|
|
10
|
|
|
const NAVIGATOR_WIDGET = 'navigator'; |
|
11
|
|
|
|
|
12
|
|
|
const FACETED_SEARCH_WIDGET = 'faceted_search'; |
|
13
|
|
|
|
|
14
|
|
|
public static function get_srcset( $post_id, $widget_name ) { |
|
15
|
|
|
|
|
16
|
|
|
$srcset = array(); |
|
17
|
|
|
$small = get_the_post_thumbnail_url( $post_id, 'small' ); |
|
18
|
|
|
$medium = get_the_post_thumbnail_url( $post_id, 'medium' ); |
|
19
|
|
|
$large = get_the_post_thumbnail_url( $post_id, 'large' ); |
|
20
|
|
View Code Duplication |
if ( $small && $width = self::get_image_width( $post_id, 'small' ) ) { |
|
|
|
|
|
|
21
|
|
|
$srcset[] = $small . ' ' . $width . 'w'; |
|
22
|
|
|
} |
|
23
|
|
View Code Duplication |
if ( $medium && $width = self::get_image_width( $post_id, 'medium' ) ) { |
|
|
|
|
|
|
24
|
|
|
$srcset[] = $medium . ' ' . $width . 'w'; |
|
25
|
|
|
} |
|
26
|
|
|
|
|
27
|
|
View Code Duplication |
if ( $large && $width = self::get_image_width( $post_id, 'large' ) ) { |
|
|
|
|
|
|
28
|
|
|
$srcset[] = $large . ' ' . $width . 'w'; |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
|
|
$srcset_string = join( ",", $srcset ); |
|
32
|
|
|
|
|
33
|
|
|
/** |
|
34
|
|
|
* Filter name: wordlift_${widget_name}_thumbnail_srcset |
|
35
|
|
|
* Filters the srcset string supplied to widgets for each post. |
|
36
|
|
|
* |
|
37
|
|
|
* @param $srcset_string string The srcset string |
|
38
|
|
|
* |
|
39
|
|
|
* @since 3.28.0 |
|
40
|
|
|
*/ |
|
41
|
|
|
$srcset_string = apply_filters( "wordlift_${widget_name}_thumbnail_srcset", $srcset_string ); |
|
42
|
|
|
|
|
43
|
|
|
return $srcset_string; |
|
44
|
|
|
|
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
|
|
48
|
|
|
private static function get_image_width( $post_id, $size ) { |
|
49
|
|
|
$thumbnail_id = get_post_thumbnail_id( $post_id ); |
|
50
|
|
|
if ( ! $thumbnail_id ) { |
|
51
|
|
|
return false; |
|
52
|
|
|
} |
|
53
|
|
|
$data = wp_get_attachment_image_src( $thumbnail_id, $size ); |
|
54
|
|
|
if ( ! $data ) { |
|
55
|
|
|
return false; |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
return array_key_exists( 2, $data ) ? $data[2] : false; |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
|
|
62
|
|
|
} |
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.