Check php version before theme activation

I’ve got theme that requires php 5.3+ version. If older – fatal error occurs with it.

So what I need to do when user try to activate this theme is to check php version before going into theme code and then, if php version is too old, show some message and don’t activate my theme, but stay with the one that was active before

Read More

Is it possible?

I’ve got this code to check version

define("THEME_REQUIRED_PHP_VERSION", '5.3.0');
define("THEME_IGNORE_PHP_VERSION", 0);

        //check if good php version
        if ( !THEME_IGNORE_PHP_VERSION&& version_compare(phpversion(), THEME_REQUIRED_PHP_VERSION, '<')) {
            // php version isn't high enough
            wp_die("<h2>You need to update php version.</h2>Too old version of PHP to run Circle Theme. Actual version is <strong>" . phpversion() . "</strong>, required is <strong>" . CIRCLE_REQUIRED_PHP_VERSION . "</strong>.", "Theme");
        }

However this cannot be becouse theme is activated anyway and user can’t do anything.

Related posts

1 comment

  1. 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.

Comments are closed.