Skip to main content

Programmatically install and activate a design template

Free Intermediate Since v1.0.0

Use TemplateUpload from the container to install a zip and activate it in a single call — useful for add-ons that bundle a companion template and auto-install it on first activation. Guard with get_active() !== null to avoid overriding the user’s chosen template. Wrap in try/catch — a failed install should display an admin notice, not fatal.

Code

<?php
add_action( 'benecaster_boot', function ( \Benecaster\Container $c ): void {
    $uploader = $c->make( \Benecaster\Template\TemplateUpload::class );
    if ( $uploader->get_active() !== null ) {
        return; // a template is already active, don't override the user's choice
    }
    $zip = plugin_dir_path( __FILE__ ) . 'assets/my-template.zip';
    try {
        $manifest = $uploader->install( $zip );
        $uploader->activate( $manifest->slug );
    } catch ( \RuntimeException $e ) {
        // log or display admin notice — do not fatal
    }
} );