最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Check and load class of theme from a plugin

programmeradmin1浏览0评论

I'm in the process of breaking down a theme to a bunch of plugins, I wanna do it one by one so hell won't break loose.

Question is, Suppose I have a plugin which depends on a class from the theme, where and how should I validate his existence and load it, and if not exist how do I properly show an error and avoid loading the plugin, is it on the activation hook? I'm pretty new to plugins, and would love to get best practices, or any good docs references regarding my issue, thanks!

I don't need to check another plugins existence, just another code that is currently part of the theme.

I'm in the process of breaking down a theme to a bunch of plugins, I wanna do it one by one so hell won't break loose.

Question is, Suppose I have a plugin which depends on a class from the theme, where and how should I validate his existence and load it, and if not exist how do I properly show an error and avoid loading the plugin, is it on the activation hook? I'm pretty new to plugins, and would love to get best practices, or any good docs references regarding my issue, thanks!

I don't need to check another plugins existence, just another code that is currently part of the theme.

Share Improve this question edited Mar 30, 2019 at 6:04 Chen Kinnrot asked Mar 28, 2019 at 5:52 Chen KinnrotChen Kinnrot 1136 bronze badges 2
  • Could you give an example of such class? It all depends... – Krzysiek Dróżdż Commented Mar 28, 2019 at 6:41
  • Possible duplicate of Check if a class exists within a method – norman.lol Commented Mar 28, 2019 at 7:31
Add a comment  | 

1 Answer 1

Reset to default 1

I'd recommend to not use methods from your theme in the plugins. Only the other way around. Let your plugins provide methods to be used in the theme. Then you could simply use is_plugin_active().


Nonetheless you could use PHP's class_exists() to check for the existence of a class. Another common practice seems to be to let your plugin die; at the very top before anything else can be loaded.

<?php
/*
Plugin Name: My Plugin
Description: Lorem ipsum dolor sit amet.
Version: 1.0
Author: You
Author URI: https://example
*/

if ( ! class_exists('MyThemeClass') ) {
  die;
}

class MyPlugin() {
  // ...
}

new MyPlugin;
发布评论

评论列表(0)

  1. 暂无评论