Enqueue scripts and styles via shortcode

[ad_1]

Hey everyone,

I want to make a shortcode that includes some css and js for datatables. I only want to enqueue those scripts on pages where the shortcode is on tho.

How is this possible?

function shortcode_callback(){
    wp_enqueue_style('datatables', 'pathtocss');
    wp_enqueue_script('datatables', 'pathtojs');
    //rest of shortcode
}

Is this possible? Isn’t it recommended to enqueue styles and scripts on the action wp_enqueue_scripts? What if I wrap the enqueue_styles and enqueue_scripts in

function shortcode_callback(){
   add_action('wp_enqueue_scripts', function(){
       wp_enqueue_style('datatables', 'pathtocss');
       wp_enqueue_script('datatables', 'pathtojs');
   });
} 

would that work? I don’t think this is right since the shortback will be executed after the initial do_action(‘wp_enqueue_scripts’); right?

 

This site will teach you how to build a WordPress website for beginners. We will cover everything from installing WordPress to adding pages, posts, and images to your site. You will learn how to customize your site with themes and plugins, as well as how to market your site online.

Buy WordPress Transfer