-
Notifications
You must be signed in to change notification settings - Fork 0
/
Extend-REST-api.php
110 lines (95 loc) · 2.89 KB
/
Extend-REST-api.php
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
<?php
/**
* Plugin Name: TSL-extend-REST-api
* Plugin URI: https://github.com/bahiirwa/TSL-extend-REST-api/
* Description: Extend the post featured images to the rest API programtically and safely on a high level.
* Version: 1.1.0
* Author: Laurence Bahiirwa
* Author URI: https://omukiga.com
* Requires at least: 3.0
* Tested up to: 4.9.5
* Tags: Extend, REST-api, featured-images
* Text Domain: tsl
* License: GPLv2
*
**/
add_action('rest_api_init', 'register_rest_images' );
function register_rest_images(){
register_rest_field( array('post'),
'fimg_url',
array(
'get_callback' => 'get_rest_featured_image',
'update_callback' => null,
'schema' => null,
)
);
register_rest_field( array('post'),
'featimgs_url',
array(
'get_callback' => 'get_rest_attached_images',
'update_callback' => null,
'schema' => null,
)
);
register_rest_field( array('post'),
'attached_imgs_url',
array(
'get_callback' => 'get_rest_attached_images_minus_feat',
'update_callback' => null,
'schema' => null,
)
);
register_rest_field( array('post'),
'user_display_name',
array(
'get_callback' => 'get_rest_user_display_name',
'update_callback' => null,
'schema' => null,
)
);
register_rest_field( array('post'),
'author_user_description',
array(
'get_callback' => 'get_rest_user_description',
'update_callback' => null,
'schema' => null,
)
);
}
function get_rest_featured_image( $object, $field_name, $request ) {
if( $object['featured_media'] ){
$img = wp_get_attachment_image_src( $object['featured_media'], 'app-thumb' );
return $img[0];
}
return false;
}
function get_rest_attached_images() {
$media = get_attached_media('image', get_the_ID());
return $media;
}
//All other attached images minus the featured image.
function get_rest_attached_images_minus_feat() {
$output = "";
if( has_post_thumbnail() ):
$output = wp_get_attachment_url( get_post_thumbnail_id( get_the_ID() ) );
else:
if($attachment):
foreach($attachments as $attachment):
$output = wp_get_attachment_url( $attachment->ID);
endforeach;
endif;
wp_reset_postdata();
endif;
$attachments = get_posts(array(
'post_type'=> 'attachment',
'posts_per_page' => -1,
'post_parent' => get_the_ID()
));
return $output;
}
function get_rest_user_display_name() {
return get_the_author();
}
function get_rest_user_description() {
return get_the_author_description();
}