0

I created a helper class to extend other classes for shortcodes.

When I try to use $this in the add_shortcode() function I'm getting this error:

Using $this when not in object context

How can I solve this?

Code below:

Parent Class

//shortcode-helper.php
abstract class ShortcodeHelper {

    private $post_name_id;
    private $short_code_name;

    /**
     * ShortcodeHelper constructor.
     *
     * @param $post_name_id
     * @param $short_code_name
     */
    protected function __construct( $post_name_id, $short_code_name ) {
        $this->post_name_id      = $post_name_id;
        $this->short_code_name   = $short_code_name;
    }

    /**
     * Sets shortcode for the ShortcodeHelper
     */
    public function register() {
        add_shortcode( $this->short_code_name, $this->do_frontend_shortcode() );
    }

    protected function do_frontend_shortcode() {
        echo 'Test! '.$this->metabox_id;
    }
}

Child Class

//test-form.php
    class TestForm extends ShortcodeHelper {

        /**
         * TestForm constructor.
         */
        public function __construct() {
            parent::__construct(
                //post_name_id
                'about_us',
                //short_code_name
                'cmb-about-form'
            );
        }
    }

    new TestForm();
1
  • What did you find when you searched for this error?
    – Tim Malone
    Jul 26, 2016 at 10:56

1 Answer 1

1

If you are targeting class method you need to pass an array where first argument is class instance and second is method name as string.

Your add_shortcode line should look like this:

add_shortcode($this->short_code_name, array($this, 'do_frontend_shortcode'));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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