-
Notifications
You must be signed in to change notification settings - Fork 5
Register Shortcode
ecorica edited this page Jul 23, 2021
·
1 revision
If you want to add shortcodes in your plugin you can :
- Create a Shortcodes folder
Shortcodes/
- Add the abstract class Shortcode.php
<?php
namespace BEA\PB\Shortcodes;
/**
* This class is the base class of Shortcode
* It have to be used as base for all Shortcodes
*
* Class Shortcode
*
* @package BEA\PB\Shortcodes
* @since 2.1.0
*/
abstract class Shortcode {
/**
* The shortcode [tag]
* @var string
* @since 2.1.0
*/
protected $tag = '';
/**
* List of supported attributes and their defaults
*
* @var array
* @since 2.1.0
*/
protected $defaults = [];
/**
* Create a shortcode
*
* @since 2.1.0
*/
public function add(): void {
add_shortcode( $this->tag, [ $this, 'render' ] );
}
/**
* Combine the attributes gives us whit defaults attributes
*
* @since 2.1.0
*
* @param array $attributes
*
* @return mixed
*/
public function attributes( $attributes = [] ) {
return shortcode_atts( $this->defaults, $attributes, $this->tag );
}
/**
* Display shortcode content
*
* @since 2.1.0
*
* @param array $attributes
* @param string $content
*
* @return string
*/
abstract public function render( $attributes = [], $content = '' );
}
- Add the Shortcode Factory class
<?php
namespace BEA\PB\Shortcodes;
/**
* The purpose of this factory is to create shortcodes easily
*
* The usage of the class is something like this :
*
* Shortcode_Factory::register( 'My_Shortcode_Class' );
*
* My_Shortcode_Class have to be a child of Shortcode class
*
* Class Shortcode_Factory
*
* @package BEA\PB\Shortcodes
* @since 2.1.0
*/
class Shortcode_Factory {
/**
* Instantiate a shortcode with the given class
* Do not specify the namespace
*
* @param string $class_name : Shortcode the Shortcode ClassName to register
*
* @return Shortcode|\WP_Error Instance of the Shortcode added or false on failure
* @since 2.1.0
*/
public static function register( string $class_name ) {
$class_name = __NAMESPACE__ . '\\' . $class_name;
if ( empty( $class_name ) || ! class_exists( $class_name ) || ! is_subclass_of( $class_name, Shortcode::class ) ) {
return new \WP_Error( 'fail_shortcode_registration', sprintf( 'Fail to instantiate shortcode %s', $class_name ) );
}
/**
* Since the shortcodes are Singleton we only have to get the instance
* and call the add method
*
* @var Shortcode $class
*/
try {
/** @psalm-suppress UnsafeInstantiation */
$class = new $class_name();
$class->add();
} catch ( \Exception $e ) {
return new \WP_Error( 'fail_shortcode_instanciation', sprintf( 'Fail to instantiate shortcode with error %s', $e->getMessage() ) );
}
return $class;
}
}