[resolved] Shortcodes from a Class (3 posts)

  1. TheGremlyn
    Posted 2 years ago #

    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?

  2. Chris
    Posted 2 years ago #

    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.

  3. TheGremlyn
    Posted 2 years ago #

    Brilliant, exactly what I needed!

Topic Closed

This topic has been closed to new replies.

About this Topic