| 1 |
<?php |
| 2 |
|
| 3 |
class Code_Snippets_Shortcode { |
| 4 |
|
| 5 |
function __construct() { |
| 6 |
add_shortcode( 'code_snippet', array( $this, 'render_shortcode' ) ); |
| 7 |
add_action( 'the_posts', array( $this, 'enqueue_prism' ) ); |
| 8 |
} |
| 9 |
|
| 10 |
function enqueue_prism( $posts ) { |
| 11 |
|
| 12 |
if ( empty( $posts ) || code_snippets_get_setting( 'general', 'disable_prism' ) ) { |
| 13 |
return $posts; |
| 14 |
} |
| 15 |
|
| 16 |
$found = false; |
| 17 |
|
| 18 |
foreach ( $posts as $post ) { |
| 19 |
|
| 20 |
if ( false !== stripos( $post->post_content, '[code_snippet' ) ) { |
| 21 |
$found = true; |
| 22 |
break; |
| 23 |
} |
| 24 |
} |
| 25 |
|
| 26 |
if ( ! $found ) { |
| 27 |
return $posts; |
| 28 |
} |
| 29 |
|
| 30 |
$plugin = code_snippets(); |
| 31 |
|
| 32 |
wp_enqueue_style( |
| 33 |
'code-snippets-prism', |
| 34 |
plugins_url( 'js/vendor/prism.css', $plugin->file ), |
| 35 |
array(), $plugin->version |
| 36 |
); |
| 37 |
|
| 38 |
wp_enqueue_script( |
| 39 |
'code-snippets-prism', |
| 40 |
plugins_url( 'js/vendor/prism.js', $plugin->file ), |
| 41 |
array(), $plugin->version, true |
| 42 |
); |
| 43 |
|
| 44 |
return $posts; |
| 45 |
} |
| 46 |
|
| 47 |
function render_shortcode( $atts ) { |
| 48 |
|
| 49 |
$atts = shortcode_atts( |
| 50 |
array( |
| 51 |
'id' => 0, |
| 52 |
'network' => false, |
| 53 |
), |
| 54 |
$atts, 'code_snippet' |
| 55 |
); |
| 56 |
|
| 57 |
if ( ! $id = intval( $atts['id'] ) ) { |
| 58 |
return ''; |
| 59 |
} |
| 60 |
|
| 61 |
$network = $atts['network'] ? true : false; |
| 62 |
$snippet = get_snippet( $id, $network ); |
| 63 |
|
| 64 |
if ( ! trim( $snippet->code ) ) { |
| 65 |
return ''; |
| 66 |
} |
| 67 |
|
| 68 |
return '<pre><code class="language-php">' . esc_html( $snippet->code ) . '</code></pre>'; |
| 69 |
} |
| 70 |
} |
| 71 |
|
| 72 |
|