| 1 |
<?php |
| 2 |
|
| 3 |
if (!defined('ABSPATH')) |
| 4 |
exit; // Exit if accessed directly |
| 5 |
|
| 6 |
class AIBUI_JS_Handler |
| 7 |
{ |
| 8 |
/** |
| 9 |
* Clés de post meta contenant du JavaScript ré-émis tel quel sur le front. |
| 10 |
*/ |
| 11 |
const JS_META_KEYS = array( |
| 12 |
'ai_builder_page_js_content', |
| 13 |
'ai_builder_block_js_content', |
| 14 |
'ai_builder_js_content', |
| 15 |
); |
| 16 |
|
| 17 |
public function __construct() |
| 18 |
{ |
| 19 |
// Ajouter le JS personnalisé sur le frontend |
| 20 |
add_action('wp_footer', array($this, 'add_custom_js')); |
| 21 |
|
| 22 |
// Marquer les meta JS comme protégées : elles ne peuvent alors plus être |
| 23 |
// écrites via la boîte « Champs personnalisés » de l'éditeur ni via XML-RPC |
| 24 |
// par un utilisateur qui a seulement edit_post. Le seul point d'écriture |
| 25 |
// reste le handler AJAX, gardé par unfiltered_html. |
| 26 |
add_filter('is_protected_meta', array($this, 'protect_js_meta'), 10, 3); |
| 27 |
} |
| 28 |
|
| 29 |
/** |
| 30 |
* @param bool $protected |
| 31 |
* @param string $meta_key |
| 32 |
* @param string $meta_type |
| 33 |
* @return bool |
| 34 |
*/ |
| 35 |
public function protect_js_meta($protected, $meta_key, $meta_type) |
| 36 |
{ |
| 37 |
if ($meta_type === 'post' && in_array($meta_key, self::JS_META_KEYS, true)) { |
| 38 |
return true; |
| 39 |
} |
| 40 |
return $protected; |
| 41 |
} |
| 42 |
|
| 43 |
public function add_custom_js() |
| 44 |
{ |
| 45 |
// Récupérer l'ID du post actuel |
| 46 |
$post_id = get_the_ID(); |
| 47 |
|
| 48 |
if (!$post_id) { |
| 49 |
return; |
| 50 |
} |
| 51 |
|
| 52 |
// Récupérer le JS personnalisé depuis les meta du post |
| 53 |
$js_content = get_post_meta($post_id, 'ai_builder_js_content', true); |
| 54 |
|
| 55 |
if (!empty($js_content)) { |
| 56 |
echo '<script id="ai-builder-frontend-js" type="text/javascript">' . $js_content . '</script>'; |
| 57 |
} |
| 58 |
} |
| 59 |
} |
| 60 |
|
| 61 |
new AIBUI_JS_Handler(); |
| 62 |
|