I am currently writing my first WordPress plugin. Since I am pretty sure this will not be my last one, I try to put as much code as possible into common code files for later reuse in other plugins.
I am using namespaces and OOP programming to allow the code being reused like I do in my C++ projects (as far as PHP allows to do so).
However in WordPress/PHP there is a problem with no obvious solution: Where should I place the shared code files? WordPress kind of merges all the code in a global application. So copying code into each plugin folder could mean potential collisions and/or random use of code files with same content, but different stages of development. Also this would create ugly redundancies.
I did not find a dedicated central storage place.
Placing the shared code in the “plugins” folder is a bad idea since each shared code file would be considered a separate plugin.
I could add all the shared code by means of a special library plugin (as far as I know, this would make the contained code visible to all other plugins), but this seems kind of weird. Also I am not sure if this would be reliable.
What is the best solution?
WordPress kind of sucks with reusability in plugins.
As far as I know, there isn’t any integrated way to reuse code in WordPress plugins.
You can try out Plugin Dependencies plugin to manage dependencies between your plugins. So you can store your generic code under one plugin that will be required by others.
Other approach would be using WordPress hooks/actions system. So you will have to defer your plugin init until the library plugin hook executes.
There are activation/deactivation hooks, so you can do some stuff when the framework is missing.
Take a look a these pages:
Regarding adamiscoding’s answer: I am trying the proposed hook solution, pushing the framework-plugin to first place in the plugin loading queue. I found some code snippets that should allow to do so, like the following one:
I disable to dependent plugins entirly if the framework plugin was not installed/activated, so I don’t get a bunch errors about missing definitions when loading the plugin administration page in that case. I am using the following check for this:
This seems to work fine.
Currently I am a bit unsure what I should do in case of missing framework. I could automatically deactivate it. Or I could show a persistent admin message… but that isn’t that easy, because I get a warning about some characters of “unexpected output” when activating the depended plugin due to the message code line:
This is why I try to check if the plugin code is executed during activation, so I can suppress the message in that case:
This seems to work too but I wonder if there is a better way to check if a plugin is executed during activation than
function_exists('is_plugin_active')
?