-
Notifications
You must be signed in to change notification settings - Fork 2
/
shortcode-notes.php
99 lines (74 loc) · 2.45 KB
/
shortcode-notes.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
<?php
namespace WechangeCollection;
/**
* List WECHANGE notes
*/
// Notes shortcode
function output_wechange_notes( $atts ) {
$atts = shortcode_atts(
array(
'url' => trailingslashit( WECHANGE_BASE_URL ),
'parameters' => '',
),
$atts,
'wechange_notes'
);
$url = $atts['url'];
$parameters = $atts['parameters'];
$api_url = $url . '/api/v2/notes/?' . $parameters;
$url_hash = wp_hash( $api_url, 'nonce' );
$lang = apply_filters( 'wpml_current_language', NULL ); // WPML support
if ( false === ( $notes_html = get_transient( 'wechance-collection-notes-' . $url_hash . $lang ) ) ) {
// It wasn't there, so regenerate the data and save the transient
$notes_html = get_notes_from_api( $api_url );
set_transient(
'wechance-collection-notes-' . $url_hash . $lang,
$notes_html,
apply_filters( 'wechange_collection_cache_time_notes', wechange_collection_cache_time() )
);
}
return $notes_html;
}
add_shortcode( 'wechange_notes', __NAMESPACE__ . '\output_wechange_notes' );
function get_notes_from_api( $url ) {
$notes = array();
$handle = curl_init();
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_URL, $url);
$result = curl_exec($handle);
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
curl_close($handle);
if ($httpCode == 200) {
$result = json_decode($result);
// Add domain to each note
$domain = parse_url($url)['host'];
foreach ($result->results as $result) {
$result->domain = $domain;
$notes[] = $result;
}
}
if ( empty($notes) ) {
return 'No notes found';
}
$notes_html_main = [];
foreach ( $notes as $note ) {
$notes_html_main[] = get_note_html( $note );
}
$notes_html_main = implode( $notes_html_main );
$notes_html_before = apply_filters( 'wechange_collection_notes_html_before', '<section class="wechange-notes">');
$notes_html_after = apply_filters( 'wechange_collection_notes_html_after', '</section>');
$notes_html = $notes_html_before . $notes_html_main . $notes_html_after;
return $notes_html;
}
function get_note_html( $note ) {
ob_start();
$Parsedown = new \Parsedown();
$note->text = $Parsedown->setSafeMode(true)->text( $note->text );
$template_loader = new WechangeCollection_Template_Loader;
$template_loader->set_template_data( [ 'note' => $note ] )
->get_template_part( 'note' );
// Store output buffer
$note_html = ob_get_clean();
return $note_html;
}