Autogenerate wordpress shortcodes using array?

Auto-generate shortcodes from an array:

You can try the following Shortcode Automat:

/**
 * Setup the Shortcode Automat
 *
 */

function shortcode_automat_setup()
{   
    $settings = array(
        "get_address"   =>  "mg_admin_address",
        "get_phone"     =>  "mg_admin_phone",
        "get_fax"       =>  "mg_admin_fax",
        "get_email"     =>  "mg_admin_email",
        "get_hrs_mon"   =>  "mg_work_hrs_mon_frd",
        "get_hrs_sat"   =>  "mg_work_hrs_sat"
    );

    $sc = new ShortCodeAutomat( $settings );
    $sc->generate();
}

add_action( 'wp_loaded', 'shortcode_automat_setup' );

You can then test it from your theme/plugin with:

echo do_shortcode( "[get_address]" );
echo do_shortcode( "[get_phone]" );
echo do_shortcode( "[get_fax]" );

or test it with:

[get_address]
[get_phone]
[get_fax]

within your post/page content.

Here is our demo class definition:

/**
 * class ShortCodeAutomat
 */

class ShortCodeAutomat
{
    protected $settings = array();

    public function  __construct( $settings = array() )
    {
        $this->settings = $settings;
    }

    public function __call( $name, $arguments )
    {
        if( in_array( $name, array_keys( $this->settings ) ) )
        {
            return get_option( sanitize_key( $this->settings[$name] ), '' );
        }
    }

    public function generate()
    {
        foreach( $this->settings as $shortcode => $option )
        {
            add_shortcode( $shortcode, array( $this, $shortcode ) );
        }
    }
} // end class

Leave a Comment