I am creating a new plugin and have decided to use WordPress Plugin Boilerplate.
However, I'm not sure where the correct place is to call WP's add_shortcode
. I'm stuck on two counts:
add_shortcode
doesn't usually have a hook - so I doubt I would call it via my define_admin_hooks
or define_public_hooks
functions.add_shortcode
now that everything is object orientated.So where is the best place for me to call add_shortcode
? A short example/snippet would be much appreciated.
I am creating a new plugin and have decided to use WordPress Plugin Boilerplate.
However, I'm not sure where the correct place is to call WP's add_shortcode
. I'm stuck on two counts:
add_shortcode
doesn't usually have a hook - so I doubt I would call it via my define_admin_hooks
or define_public_hooks
functions.add_shortcode
now that everything is object orientated.So where is the best place for me to call add_shortcode
? A short example/snippet would be much appreciated.
Add the below function in /includes/class-plugin-loader.php
:
public function add_shortcode( $tag, $component, $callback, $priority = 10, $accepted_args = 2 ) {
$this->shortcodes = $this->add( $this->shortcodes, $tag, $component, $callback, $priority, $accepted_args );
}
You can then define your shortcode in /includes/class-plugin.php
within this function:
/**
* Register all of the hooks related to the public-facing functionality
* of the plugin.
*
* @since 1.0.0
* @access private
*/
private function define_public_hooks() {
$plugin_public = new Plugin_Public( $this->get_plugin_name(), $this->get_version() );
$this->loader->add_action( 'wp_enqueue_scripts', $plugin_public, 'enqueue_styles' );
$this->loader->add_action( 'wp_enqueue_scripts', $plugin_public, 'enqueue_scripts' );
$this->loader->add_shortcode( 'YOUR-SHORTCODE-NAME', $plugin_public, 'YOUR_CALLBACK_FUNCTION' );
}
Finally add your callback function in the /public/class-plugin-public.php
like this:
public function YOUR_CALLBACK_FUNCTION( $atts ){
// do your shortcode stuff
}
Change plugin
in the filenames above with your own plugin name.
The above code is pretty much correct however those hooks should be registered as add_shrotcode where the actions and filters are. So Here is the full implementation code.
Step: 1 on -> class-plugin-loader.php
Add the $shortcode property as protected
protected $shortcodes;
public function add_shortcode( $tag, $component, $callback, $priority = 10, $accepted_args = 2 ) {
$this->shortcodes = $this->add( $this->shortcodes, $tag, $component, $callback, $priority, $accepted_args );
}
Step 2: Now you have to register all of your passing shortcodes where the actions and filters hooks are
on the run method after the previous filters and actions hooks foreach functions put the below code
if ( isset( $this->shortcodes ) ) {
foreach ( $this->shortcodes as $shortcode ) {
add_shortcode( $shortcode['hook'], array( $shortcode['component'], $shortcode['callback'] ) );
}
}