官术网_书友最值得收藏!

Checking WordPress versions

It is common for scripts to perform some "pre-flight" tests at runtime to ensure that they can execute correctly. Common examples of these types of tests include checking the version of PHP or of WordPress. To avoid any potential catastrophes that could occur if our plugin is activated on incompatible WordPress versions, we will perform a simple WordPress version check, and you can use this format as a guideline for how you might perform similar pre-flight tests. Let's add another PHP constant to define the minimum version of WordPress required. We want this plugin to require WordPress version 3 or greater:

define('DIGGTHIS_MIN_WORDPRESS_VERSION', '3.0');

Again, we place this near the top of our plugin in the area we allotted for configuration and settings.

In order to check the current version of WordPress, we can use the global WordPress variable $wp_version. We can then use the PHP function version_compare() to compare the current version with the minimum required. The following is how we updated the diggthis_check_wordpress_version() function:

/**
* Checks that the current version of WordPress is current enough.
*
* @return   none   exit on fail.
*/
function diggthis_check_wordpress_version() {
   global $wp_version;
   
   $exit_msg='"Digg This" requires WordPress '
      .DIGGTHIS_MIN_WORDPRESS_VERSION
      .' or newer. 
      <a >Please update!</a>';
      
   if (version_compare($wp_version,DIGGTHIS_MIN_WORDPRESS_VERSION,'<'))
   {
       exit ($exit_msg);
   }
}

This will ensure that only users who are running WordPress 3.0 or later will be able to use the plugin. Technically, everything we've done would work on many older versions of WordPress, but since we authored this plugin on WordPress 3, it's best not to assume that it will work on older versions.

To execute this function, we will tie into the same init method as we did before. Simply add this below our existing add_action() and add_filter() functions:

add_action('init', 'diggthis_check_wordpress_version');

To ensure that this works, try temporarily changing the minimum version constant:

define('DIGGTHIS_MIN_WORDPRESS_VERSION', '4.0');

Save your file and refresh your browser. You should see the $exit_msg displayed:

"Digg This" requires WordPress 4.0 or newer. Please update!

Once you've verified that the error message works, you can change the constant back.

主站蜘蛛池模板: 清流县| 五河县| 松原市| 乌兰察布市| 集安市| 扶绥县| 鲁甸县| 合川市| 平舆县| 宣城市| 辉南县| 崇信县| 巫溪县| 肃宁县| 宣汉县| 泗洪县| 兴隆县| 山丹县| 河津市| 万宁市| 安新县| 稷山县| 西峡县| 萨嘎县| 镇江市| 佛坪县| 汾西县| 花垣县| 德江县| 无极县| 绥阳县| 泰兴市| 南昌县| 阿瓦提县| 兴和县| 沛县| 雷州市| 辉县市| 扶绥县| 阿拉尔市| 湘西|