Check php version before theme activation

As you want to implement the check within your theme files you can use the action after_switch_theme; as you can guess this will activate your theme to perform the check but will switch back to the previous theme if necessary.

If the requirements are not fulfilled we’re going to notify the user via an admin notice (via the action admin_notices) and instantly switch back to the previous theme. You’ll retrieve the details of the previous theme via get_option('theme_switched')

// Minimum required version.
define( 'THEME_REQUIRED_PHP_VERSION', '5.3.0' );

add_action( 'after_switch_theme', 'check_theme_setup' );
function check_theme_setup(){

  // Compare versions.
  if ( version_compare(phpversion(), THEME_REQUIRED_PHP_VERSION, '<') ) :

  // Theme not activated info message.
  add_action( 'admin_notices', 'my_admin_notice' );
  function my_admin_notice() {
  ?>
    <div class="update-nag">
      <?php _e( 'You need to update your PHP version to run Circle Theme.', 'text-domain' ); ?> <br />
      <?php _e( 'Actual version is:', 'text-domain' ) ?> <strong><?php echo phpversion(); ?></strong>, <?php _e( 'required is', 'text-domain' ) ?> <strong><?php echo THEME_REQUIRED_PHP_VERSION; ?></strong>
    </div>
  <?php
  }

  // Switch back to previous theme.
  switch_theme( $old_theme->stylesheet );
    return false;

  endif;
}

You can use this code within your functions.php but also within an additional plugin. If you’re using it within a plugin you can move the checkpoint after_switch_theme to a prior action to avoid theme activation.

Leave a Comment