| 1 |
<?php |
| 2 |
|
| 3 |
namespace Code_Snippets; |
| 4 |
|
| 5 |
/** |
| 6 |
* Class for loading active snippets of various types. |
| 7 |
* |
| 8 |
* @package Code_Snippets |
| 9 |
*/ |
| 10 |
class Active_Snippets { |
| 11 |
|
| 12 |
/** |
| 13 |
* List of content snippets. |
| 14 |
* |
| 15 |
* @var array |
| 16 |
*/ |
| 17 |
private $content_snippets = []; |
| 18 |
|
| 19 |
/** |
| 20 |
* Class constructor. |
| 21 |
*/ |
| 22 |
public function __construct() { |
| 23 |
add_action( 'init', array( $this, 'init' ) ); |
| 24 |
} |
| 25 |
|
| 26 |
/** |
| 27 |
* Initialise class functions. |
| 28 |
*/ |
| 29 |
public function init() { |
| 30 |
$db = code_snippets()->db; |
| 31 |
$this->content_snippets = $db->fetch_active_snippets( [ 'head-content', 'footer-content' ], 'code, scope' ); |
| 32 |
|
| 33 |
add_action( 'wp_head', [ $this, 'load_head_content' ] ); |
| 34 |
add_action( 'wp_footer', [ $this, 'load_footer_content' ] ); |
| 35 |
} |
| 36 |
|
| 37 |
/** |
| 38 |
* Print snippet code fetched from the database from a certain scope. |
| 39 |
* |
| 40 |
* @param array $snippets_list List of data fetched. |
| 41 |
* @param string $scope Name of scope to print. |
| 42 |
*/ |
| 43 |
private function print_content_snippets( $snippets_list, $scope ) { |
| 44 |
foreach ( $snippets_list as $snippets ) { |
| 45 |
foreach ( $snippets as $snippet ) { |
| 46 |
if ( $scope === $snippet['scope'] ) { |
| 47 |
// phpcs:disable WordPress.Security.EscapeOutput.OutputNotEscaped |
| 48 |
echo "\n", $snippet['code'], "\n"; |
| 49 |
} |
| 50 |
} |
| 51 |
} |
| 52 |
} |
| 53 |
|
| 54 |
/** |
| 55 |
* Print head content snippets. |
| 56 |
*/ |
| 57 |
public function load_head_content() { |
| 58 |
$this->print_content_snippets( $this->content_snippets, 'head-content' ); |
| 59 |
} |
| 60 |
|
| 61 |
/** |
| 62 |
* Print footer content snippets. |
| 63 |
*/ |
| 64 |
public function load_footer_content() { |
| 65 |
$this->print_content_snippets( $this->content_snippets, 'footer-content' ); |
| 66 |
} |
| 67 |
} |
| 68 |
|