[wp-trac] [WordPress Trac] #54958: Inconsistent behaviour for wp_add_inline_script between block-based and standard themes
WordPress Trac
noreply at wordpress.org
Tue Mar 12 16:41:53 UTC 2024
#54958: Inconsistent behaviour for wp_add_inline_script between block-based and
standard themes
---------------------------+------------------------------
Reporter: Rustaurius | Owner: (none)
Type: defect (bug) | Status: closed
Priority: normal | Milestone: Awaiting Review
Component: Script Loader | Version:
Severity: normal | Resolution: invalid
Keywords: | Focuses:
---------------------------+------------------------------
Changes (by codespacing):
* status: reopened => closed
* resolution: => invalid
Comment:
The approach that worked for me and aligns with the recommended method of
loading scripts in WordPress consists of checking if the theme is a "Full-
site-editing (FSE) / block" theme or classic using the WP function
{{{wp_is_block_theme}}}. Then, enqueue the scripts in the standard manner
for classic themes or use the hook {{{wp_enqueue_scripts}}} for FSE/block
themes. This approach is applicable within shortcode callbacks. And of
course this approach is applicable within shortcode callbacks. Here's an
example:
{{{#!php
<?php
class CustomShortcode {
// Constructor
public function __construct() {
add_shortcode('custom_html', array($this, 'display_custom_html'));
add_action('wp_enqueue_scripts', array($this, 'register_script'));
// Register scripts
}
static function this(){
return self::$_this;
}
public function register_script(){
wp_register_script('my-script-handle', plugin_dir_url( __FILE__ )
. 'script.js', array(), '1.0', true);
}
public function enqueue_script($inline_script_data){
wp_enqueue_script('my-script-handle');
wp_add_inline_script('my-script-handle', $inline_script_data);
}
// Shortcode callback function
public function display_custom_html($atts) {
/**
* Enqueue scripts based on the type of the theme
* Note: "wp_script_is()" serves as a fallback for no-theme
platforms, which cannot be detected using "wp_is_block_theme()"! */
$inline_script = 'You inline script goes here';
if(wp_is_block_theme() || !wp_script_is('my-script-handle',
'registered')){
add_action('wp_enqueue_scripts', function() use
($inline_script){
$this->enqueue_script($inline_script);
});
}else{
$this->enqueue_script($inline_script);
}
$html = '<div class="custom-html">Your shortcode HTML content goes
here</div>';
return $html;
}
}
new CustomShortcode();
}}}
--
Ticket URL: <https://core.trac.wordpress.org/ticket/54958#comment:9>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform
More information about the wp-trac
mailing list