enqueue script with get_shortcode_regex

Question

I try to optimize a bit and i want to load some shortcodes only if they are found in global $post

Unfortunately its not working, the script is not loaded when i open a page which contains the shortcode.

function enqueue_script_if_shortcode_is_detected() {
    global $post;

    wp_register_script( 'leweb-widgets', get_stylesheet_directory_uri() . '/includes/leweb-widgets.php', '1.0', true );

    $pattern = get_shortcode_regex();

    if (   preg_match_all( '/'. $pattern .'/s', $post->post_content, $matches )
        && array_key_exists( 2, $matches )
        && in_array( 'leweb_suggested_events', $matches[2] )
    ) {
        wp_enqueue_script('leweb-widgets');
    }
}
add_action( 'wp_enqueue_scripts', 'enqueue_script_if_shortcode_is_detected' );
0
, , LovinQuaQua 2 years 2019-10-31T19:51:15-05:00 0 Answers 86 views 0

Leave an answer

Browse
Browse