Completed
Push — master ( df59ed...1e23ba )
by Dominik
14s queued 11s
created

isShortcodeAndDoesNotMatchId()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 5
nc 2
nop 2
dl 0
loc 7
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Flynt\TheContentFix;
4
5
use Timber\Timber;
6
use Timber\Post;
7
8
function isShortcodeAndDoesNotMatchId($postContent, $postId)
9
{
10
    preg_match('/^\[flyntTheContent id=\\\"(\d*)\\\"\]$/', $postContent, $matches);
11
    if (!empty($matches) && $matches[1] != $postId) {
12
        return true;
13
    } else {
14
        return false;
15
    }
16
}
17
18
add_filter('wp_insert_post_data', function ($data, $postArr) {
19
    if (in_array([
20
        'revision',
21
        'nav_menu_item',
22
        'attachment',
23
        'customize_changeset'
24
    ], $postArr['post_type'])) {
25
        return $data;
26
    }
27
    // check if no content was saved before, or if there is a flyntTheContent shortcode but the id does not match the post id
28
    if (empty($data['post_content']) || isShortcodeAndDoesNotMatchId($data['post_content'], $postArr['ID'])) {
29
        $data['post_content'] = "[flyntTheContent id=\"{$postArr['ID']}\"]";
30
    }
31
    return $data;
32
}, 99, 2);
33
34
add_shortcode('flyntTheContent', function ($attrs) {
35
    $postId = $attrs['id'];
36
    // in case the post id was not set correctly and is 0
37
    if (!empty($postId)) {
38
        $context = Timber::get_context();
39
        $context['post'] = new Post($postId);
40
        return Timber::fetch('templates/theContentFix.twig', $context);
41
    }
42
});
43