How to call a function from a shortcode function in an oop plugin

I’m developing an OOP plugin based on WordPress-Plugin-Boilerplate by Devin Vinson. In the includes folder, I’ve created a class for shortcodes:

class My_Plugin_Shortcodes {

    public static function foo_shortcode( $atts ) {
        
        // get parameters
        $a = shortcode_atts( array(
            'arg1' = '',
            'arg2' = '',
        ), $atts );
        
        // do something
        
        return $myFooVar;
        
    }   
        
    public static function bar_shortcode( $atts ) {
        
        // get parameters
        $a = shortcode_atts( array(
            'arg3' = '',
            'arg4' = '',
        ), $atts );
        
        // do something
        
        return $myBarVar;
        
    }   
    
}

The shortcodes are added in the primary plugin class, also in the includes folder:

class My_Plugin {

    public function __construct() {

        ...
        
        $this-load_shortcodes();
        
        ...
        
    }
    
    ...

    private function load_shortcodes() {

        $plugin_shortcodes = new My_Plugin_Shortcodes();

        add_shortcode( 'foo', array( $plugin_shortcodes, 'foo_shortcode' ) );
        add_shortcode( 'bar', array( $plugin_shortcodes, 'bar_shortcode' ) );
    
    
    }

}

So far, so good.

But a large part of what happens in Foo is identical to a large part of what happens in Bar, and I want to place the common code in a (subroutine) function that can be called by both Foo and Bar. Procedurally, that might look like this:

class My_Plugin_Shortcodes {

    public function foo_bar_subroutine( $a ) {
        
        // do something
        
        return $mySubVar;
        
    }   
        
    public static function foo_shortcode( $atts ) {
        
        // get parameters
        $a = shortcode_atts( array(
            'arg1' = '',
            'arg2' = '',
        ), $atts );
        
        // do something
        
        $myFooVar = foo_bar_subroutine( $a )
        
        return $myFooVar;
        
    }   
        
    public static function bar_shortcode( $atts ) {
        
        // get parameters
        $a = shortcode_atts( array(
            'arg3' = '',
            'arg4' = '',
        ), $atts );
        
        // do something
        
        $myBarVar = foo_bar_subroutine( $a )
        
        return $myBarVar;
        
    }   
    
}

which doesn't work because it doesn't follow OOP conventions. But I don't know how to set it up to follow both OOP conventions and WP conventions. I assume that the subroutine doesn't get declared by either add_shortcode or add_action. But, if not, how does it get in?

Topic oop shortcode plugin-development Wordpress

Category Web

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.