-
Notifications
You must be signed in to change notification settings - Fork 0
/
guten-ipsum.php
115 lines (100 loc) · 2.6 KB
/
guten-ipsum.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
111
112
113
114
115
<?php
/*
Plugin Name: Guten Ipsum
Description: Lorem Ipsum Gutenberg Block
Author: Darin Kotter
Author URI: https://darinkotter.com
Version: 0.1.0
License: GPL2+
*/
/**
* Register our block
*
* @return void
*/
function gti_register_blocks() {
if ( ! function_exists( 'register_block_type' ) ) {
add_action( 'admin_notices', 'gti_plugin_notice' );
return;
}
wp_register_script(
'blocks',
plugins_url( 'assets/js/dist/blocks.bundle.js', __FILE__ ),
array( 'wp-blocks', 'wp-element' ),
'0.1.0'
);
register_block_type( 'gti/loremipsum', array(
'attributes' => array(
'paragraphs' => array(
'type' => 'number',
'default' => 5,
),
'service' => array(
'type' => 'string',
'default' => 'bacon-ipsum',
)
),
'editor_script' => 'blocks',
'render_callback' => 'gti_render_callback'
) );
}
add_action( 'init', 'gti_register_blocks' );
/**
* Output an error message.
*
* If the Gutenberg plugin isn't active
* and the current user has permissions to
* activate plugins, show an error message
* letting them know the plugin is needed.
*
* @return void
*/
function gti_plugin_notice() {
if ( current_user_can( 'activate_plugins' ) ) :
?>
<div class="error message">
<p>The Gutenberg plugin must be active to utilize the GutenIpsum plugin. Find it here: https://wordpress.org/plugins/gutenberg/</p>
</div>
<?php
endif;
}
/**
* Render the block for the front end.
*
* TODO: Have this render all in JS, so we don't
* have this extra HTTP request.
*
* @param array $attributes Block attributes
* @return string
*/
function gti_render_callback( $attributes ) {
$service = $attributes['service'] ?: 'bacon-ipsum';
$paragraphs = $attributes['paragraphs'] ?: 5;
$url = '';
switch ( $service ) {
case 'bacon-ipsum':
$url = 'https://baconipsum.com/api/?type=meat-and-filler¶s=' . absint( $paragraphs );
break;
case 'baseball-ipsum':
$url = 'http://baseballipsum.apphb.com/api/?paras=' . absint( $paragraphs );
break;
case 'pony-ipsum':
$url = 'http://ponyipsum.com/api/?type=pony-and-filler¶s=' . absint( $paragraphs );
break;
}
$cache_key = md5( $url );
$output = get_transient( $cache_key );
if ( empty( $output ) ) {
$response = wp_remote_request( $url );
if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
return $output;
}
$body = wp_remote_retrieve_body( $response );
$content = json_decode( $body );
foreach ( $content as $p ) {
$output .= "<p>{$p}</p>";
}
set_transient( $cache_key, $output, DAY_IN_SECONDS );
}
return wp_kses_post( $output );
}