-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDynamicReplace.php
72 lines (52 loc) · 2.38 KB
/
DynamicReplace.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
<?php
function ajaxds_dynamicReplaceInit()
{
add_filter('the_content', 'ajaxds_dynamicReplaceBeforeLoad');
}
add_action('loop_start', 'ajaxds_dynamicReplaceInit');
function ajaxds_dynamicReplaceBeforeLoad($content)
{
$newContent = $content;
//All shortcodes with Dynamic Replace enabled
$shortcodesDynReplace = ajaxds_getAllDynamicReplace();
foreach ($shortcodesDynReplace as $res) {
//Closing shortcode: Find all occurences then replace them
$shortcodeName = $res->shortcode_name;
$pattern = '/\[' . $shortcodeName . '(.*?)?\](?:(.+?)?\[\/' . $shortcodeName . '\])?/';
$matches = null;
preg_match_all($pattern, $newContent, $matches);
for ($i = 0; $i < count($matches[1]); $i++) {
$fullMatch = $matches[0][$i];
if (strpos($fullMatch, '[/') !== false) {
$contentOfShortcode = $matches[2][$i];
$leftPartShortcode = explode(']', $fullMatch)[0];
$attributes = str_replace('[' . $shortcodeName, '', $leftPartShortcode);
if (strlen($attributes) > 0) {
$attributes = ' ' . $attributes;
}
$dynamicShortcodeFinal = '[wp_dynamic shortcode="' . $shortcodeName . '"' . $attributes . ']' . $contentOfShortcode . '[/wp_dynamic]';
$newContent = str_replace($fullMatch, $dynamicShortcodeFinal, $newContent);
}
}
//Self closing shortcode: Find all occurences then replace them
$pattern = '/\[' . $shortcodeName . '(.*?)?\]/'; //'/\[' . $shortcodeName . '[^.\[\]]+\]/';
$matches = null;
preg_match_all($pattern, $newContent, $matches);
for ($i = 0; $i < count($matches[0]); $i++) {
$fullMatch = $matches[0][$i];
$dynamicShortcodeFinal = ajaxds_getSelfClosingShortcode($fullMatch, $shortcodeName);
$newContent = str_replace($fullMatch, $dynamicShortcodeFinal, $newContent);
}
}
return $newContent;
}
function ajaxds_getSelfClosingShortcode($fullMatch, $shortcodeName)
{
$attributes = str_replace('[' . $shortcodeName, '', $fullMatch);
$attributes = substr($attributes, 0, -1);
if (strlen($attributes) > 0) {
$attributes = ' ' . $attributes;
}
$dynamicShortcodeFinal = '[wp_dynamic shortcode="' . $shortcodeName . '"' . $attributes . ']';
return $dynamicShortcodeFinal;
}