How do you implement shortcode using PHP and wordpress using object-oriented programming?

I am trying to build a plugin using PHP OOP, and I cannot seem to get this 1st step working. Is there a problem with this code? When I put the shortcode [rsb-archive] into a wordpress page, all it doesn’t work.

This is the code:

Read More
class RSB_Archive {
    public function __construct()
    {
        add_shortcode('rsb-archive', array($this, 'shortcode'));
    }

    public function shortcode()
    {
           // Contents of this function will execute when the blogger
          // uses the [rsb-archive] shortcode.

          echo "print this code";



    }
}

That does not seem to work. Any ideas?

Additionally, does anyone have any insight on how to debug code using PHP. I am just beginning to learn how to use it.

Thanks!

Related posts

Leave a Reply

2 comments

  1. You have to create an instance of the widget object first.

    like so;

    <?php
    
    class RSB_Archive {
    
        public function __construct() {
           // don't call add_shortcode here
           // actually, I worked with wordpress last year and
           // i think this is a good place to call add_shortcode 
           // (and all other filters) now...
        }
    
        public function shortcode() {
            echo 'doTheDoo';
        }
    }
    
    $myWidged = new RSB_Archive();
    
    add_shortcode('my-code', array($myWidget, 'shortcode'));
    
    ?>
    

    This has been answered more thoroughly

  2. You forgot to create the instance of the class RSB_Archive.
    the codes inside the constructor runs while create the object.

    class RSB_Archive {
    
    public function __construct()
    {
        add_shortcode('rsb-archive', array($this, 'shortcode'));
    }
    
    public function shortcode()
    {
           // Contents of this function will execute when the blogger
          // uses the [rsb-archive] shortcode.
    
          echo "print this code";
    
    
    
       }
    }
    
    $obj = new RSB_Archive();