I'm building a plugin using the WordPress Plugin Boilerplate by DevinVinson.
I'm adding a public shortcode function for wich I will need some resources (js and css), I want to enqueue scripts (that go in the footer) only when necessary, so I need to enqueue scripts just before the return of the shortcode.
Thanks to Fayaz answer I solved the main problem, but I still got a small one: I can't pass $this->plugin_name to shortcode function, variable I need to correctly name resources in the wp_enqueue_script
function.
As the Boilerplate provide just add_action
hooks in define_public_hooks
function, I did use that, and nested inside it the add_shortcode hook, like this:
class My_Plugin {
$plugin_public = new My_Plugin_Public( $this->get_plugin_name(), $this->get_version() );
$this->loader->add_action( 'init', $plugin_public, 'my_plugin_ajax_register_shortcode' );
}
then in my-plugin-public.php
file:
class My_Plugin_Public {
public function __construct( $plugin_name, $version ) {
$this->plugin_name = $plugin_name;
$this->version = $version;
}
public function my_plugin_ajax_register_shortcode(){
function the_actual_shortcode($atts){
$content = 'shortcode content';
wp_enqueue_script( $this->plugin_name.'_google_maps_api' ); // we don't know what $this->plugin_name is!
return $content;
}
add_shortcode('my_shortcode', the_actual_shortcode);
}
}
As you can imagine, the the_actual_shortcode
function, ignores $this->plugin_name
, how can I pass it?