Image.php
2.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
<?php
namespace AIOSEO\Plugin\Common\Schema\Graphs\Traits;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Trait that handles images for the graphs.
*
* @since 4.2.5
*/
trait Image {
/**
* Builds the graph data for a given image with a given schema ID.
*
* @since 4.0.0
*
* @param int $imageId The image ID.
* @param string $graphId The graph ID (optional).
* @return array $data The image graph data.
*/
protected function image( $imageId, $graphId = '' ) {
$attachmentId = is_string( $imageId ) && ! is_numeric( $imageId ) ? aioseo()->helpers->attachmentUrlToPostId( $imageId ) : $imageId;
$imageUrl = wp_get_attachment_image_url( $attachmentId, 'full' );
$data = [
'@type' => 'ImageObject',
'url' => $imageUrl ? $imageUrl : $imageId,
];
if ( $graphId ) {
$data['@id'] = trailingslashit( home_url() ) . '#' . $graphId;
}
if ( ! $attachmentId ) {
return $data;
}
$metaData = wp_get_attachment_metadata( $attachmentId );
if ( $metaData && ! empty( $metaData['width'] ) && ! empty( $metaData['height'] ) ) {
$data['width'] = (int) $metaData['width'];
$data['height'] = (int) $metaData['height'];
}
$caption = $this->getImageCaption( $attachmentId );
if ( ! empty( $caption ) ) {
$data['caption'] = $caption;
}
return $data;
}
/**
* Get the image caption.
*
* @since 4.1.4
*
* @param int $attachmentId The attachment ID.
* @return string The caption.
*/
private function getImageCaption( $attachmentId ) {
$caption = wp_get_attachment_caption( $attachmentId );
if ( ! empty( $caption ) ) {
return $caption;
}
return get_post_meta( $attachmentId, '_wp_attachment_image_alt', true );
}
/**
* Returns the graph data for the avatar of a given user.
*
* @since 4.0.0
*
* @param int $userId The user ID.
* @param string $graphId The graph ID.
* @return array The graph data.
*/
protected function avatar( $userId, $graphId ) {
if ( ! get_option( 'show_avatars' ) ) {
return [];
}
$avatar = get_avatar_data( $userId );
if ( ! $avatar['found_avatar'] ) {
return [];
}
return array_filter( [
'@type' => 'ImageObject',
'@id' => aioseo()->schema->context['url'] . "#$graphId",
'url' => $avatar['url'],
'width' => $avatar['width'],
'height' => $avatar['height'],
'caption' => get_the_author_meta( 'display_name', $userId )
] );
}
/**
* Returns the graph data for the post's featured image.
*
* @since 4.2.5
*
* @return string The featured image URL.
*/
protected function getFeaturedImage() {
$post = aioseo()->helpers->getPost();
return has_post_thumbnail( $post ) ? $this->image( get_post_thumbnail_id() ) : '';
}
}