Support » Plugins » Hacks » Shortcodes from a Class

  • Resolved TheGremlyn


    I have a class built for accessing my company’s API. I want to build a set of shortcodes inside a class, which extends my existing API access class. I figure this would be more efficient and cleaner than writing a bunch of functions.

    I started off with a couple of functions to get things rolling, and once they worked as expected I wrapped them up into a class. Now I keep getting the following error:

    Fatal error: Using $this when not in object context in ...

    I assume I am getting this because of how I am using add_shortcode, which is by calling:

    add_shortcode("shortcodename", array("classname", "methodname"))

    I’m guessing this tries to call the method like this: classname::methodname(), which requires my methods to be static, and any methods they call from within the class to be static as well? Is there any way around this? Or is there a different way to call shortcodes from a class without requiring them to be static?

Viewing 2 replies - 1 through 2 (of 2 total)
  • Instead of passing the classname you can also pass an instance of if (an object).

    class PluginClass {
      public function __construct( $Object ) {
        $test = add_shortcode( 'someShortcode', array( $Object, 'handleShortcode' ) );
    class CustomHandlerClass{
      public function handleShortcode( $atts, $content ) {
        // shortcode handling
    $CustomHandler  = new CustomHandlerClass();
    $Plugin         = new PluginClass( $CustomHandler );

    This way your targeted class/methods don’t need to be static.

    Brilliant, exactly what I needed!

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Shortcodes from a Class’ is closed to new replies.