-
Notifications
You must be signed in to change notification settings - Fork 3
/
wp-serverless-api.php
78 lines (62 loc) · 1.56 KB
/
wp-serverless-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
<?php
/*
Plugin Name: WP Serverless API
Plugin URI: https://github.com/getshifter/wp-serverless-api
Description: WordPress REST API to JSON File
Version: 0.2.0
Author: Shifter
Author URI: https://getshifter.io
*/
function enable_permalinks_notice() {
?>
<div class="notice notice-warning">
<p><?php _e( 'WP Serverless Redirects requires Permalinks. <a href="/wp-admin/options-permalink.php">Enable Permalinks</a>'); ?></p>
</div>
<?php
}
if ( !get_option('permalink_structure') ) {
add_action( 'admin_notices', 'enable_permalinks_notice' );
}
function compile_db(
$routes = array(
'posts',
'pages',
'media'
)
) {
$db_array = array();
foreach ($routes as $route) {
if (getenv("SHIFTER_ACCESS_TOKEN") === false) {
$url = 'https://demo.wp-api.org/wp-json/wp/v2/' . $route;
} else {
$url = esc_url( home_url( '/' ) ) . 'wp-json/wp/v2/' . $route;
}
$jsonData = json_decode( file_get_contents($url) );
$db_array[$route] = (array) $jsonData;
}
$db = json_encode($db_array);
return $db;
}
function save_db(
$db,
$file_name = 'db.json'
) {
$save_path = WP_CONTENT_DIR . '/wp-sls-api/' . $file_name;
$dirname = dirname($save_path);
if (!is_dir($dirname))
{
mkdir($dirname, 0755, true);
}
$f = fopen( $save_path , "w+" );
fwrite($f , $db);
fclose($f);
}
function build_db()
{
$db = compile_db();
save_db($db);
}
/**
* Build on Post Save
*/
add_action( 'save_post', 'build_db' );