0

In my plugin, I would like to load css only when the front-end current page is using one of my plugin shortcodes.

All my shortcodes are classes extending Shortcode class. Shortcode class helps me to automate the callback function.

Shortcode abstract class

namespace PluginFoo\Shortcodes;


abstract class Shortcode {

    public $tag;
    public $attrs;
    public $function;

    public function __construct($tag) {
        $this->attrs = array();
        $this->tag = $tag;
        $this->function = static::className().'::getCallBack';

        add_shortcode( $this->tag, $this->function );

    }

    abstract public static function className();

    abstract public static function getCallBack( $attrs ); 
}

FooShortcode class

namespace PluginFoo\Shortcodes;

class FooShortcode extends Shortcode {

    public static function getCallBack( $attrs = null ){

        add_action('wp_enqueue_scripts', array( __CLASS__, 'set_bootstrap' ) ); // <-- Here - function set_bootstrap not called !

        $output = '';

        ob_start();

        //HTML Template
         include_once 'shortcode-view.php';

        $output .= ob_get_contents();
        ob_end_clean();

        return $output;

    }

    public static function set_bootstrap() {
         wp_enqueue_style( 'bootstrapstyle', PLUGIN_DIR_URL . 'css/bootstrap.min.css' );
    }

    public static function className(){
        return __CLASS__;
    }
}

How can I call correcty the static function set_bootstrap() in add_action() inside an another static function ?

5
  • what do you mean by "Does not work" ? give more details
    – mmm
    Commented Oct 9, 2017 at 16:57
  • the function set_bootstrap() is not called.
    – J.BizMai
    Commented Oct 9, 2017 at 17:04
  • have you activated WP_DEBUG ? codex.wordpress.org/WP_DEBUG
    – mmm
    Commented Oct 9, 2017 at 17:20
  • Yes, of course. I have got any error in the debug.log file.
    – J.BizMai
    Commented Oct 9, 2017 at 17:28
  • Do you think, it's not called because the action 'wp_enqueue_scripts' was run before ?
    – J.BizMai
    Commented Oct 9, 2017 at 17:30

2 Answers 2

2

If your class is called statically you need to use get_called_class() like this:

add_action('wp_enqueue_scripts', array( get_called_class(), 'set_bootstrap' ) );

since $this is not available. This also works if the class is extended.

0
1

you can use classname::class for example:

add_shortcodes(callback::class, 'callbackmethod');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.