To implement this functionality, you can add the following code to your theme's `functions.php` file or a custom plugin.
This implementation uses `wp_enqueue_script` to handle the JS file and `wp_add_inline_script` to inject the initialization logic. This ensures the scripts are only loaded once and only when the shortcode is actually present on the page.
```php
/**
* Register the [ejcees] shortcode
*/
function register_ejcees_shortcode($atts, $content = null) {
// 1. Define default attributes and extract them
$options = shortcode_atts(array(
'mode' => 'single', // Default mode
), $atts);
// 2. Enqueue the external JS file via Attachment ID
$attachment_id = 19088;
$url = wp_get_attachment_url($attachment_id);
if ($url) {
// Register and enqueue the script
wp_enqueue_script('ejcees-obj-js', $url, array(), null, true);
// 3. Add the initialization inline script (runs only once)
$inline_init_script = "
document.addEventListener('DOMContentLoaded', () => {
const containers = document.querySelectorAll('.ejcees');
containers.forEach(container => {
const mode = container.getAttribute('mode');
if (typeof Ejcees !== 'undefined') {
new Ejcees(container, mode);
}
});
});
";
wp_add_inline_script('ejcees-obj-js', $inline_init_script);
}
// 4. Process nested shortcodes within content
$processed_content = do_shortcode($content);
// 5. Return the HTML output
return sprintf(
'<div class="ejcees" mode="%s">%s</div>',
esc_attr($options['mode']),
$processed_content
);
}
add_shortcode('ejcees', 'register_ejcees_shortcode');
```
### Key Technical Details:
* **Script Management:** Using `wp_enqueue_script` ensures that even if you use the shortcode multiple times on one page, the `ejceesobj.js` file is only requested by the browser once.
* **Inline Logic:** `wp_add_inline_script` attaches your custom DOMContentLoaded logic directly after the source file, maintaining the correct execution order.
* **Security:** `esc_attr()` is used on the `mode` attribute to prevent XSS (Cross-Site Scripting) if a user enters malicious data into the shortcode attribute.
* **Nested Content:** `do_shortcode($content)` allows you to place other shortcodes (like galleries or buttons) inside `[ejcees]...[/ejcees]`.
---
### Usage Example:
In your WordPress editor, you can now use it like this:
`[ejcees mode="mini"]This is my content or [another_shortcode][/ejcees]`