If a theme and and plugin that have a common functionality, what would be the best way to share it?
An example for this is a theme and plugin (e.g. recent posts widget) using the same template part, for example,
content-post.php. Or a function that both theme and plugin uses?
The idea is that theme can be dependent on the plugin, but plugin should also have ability function separately. Is the only way to duplicate templates / function?
The important thing is to make plugin and theme completely functional on their own. Let’s take a look at Codex definition of both theme and plugin:
The role of a theme is to create the design and functionality, the role of a plugin is to modify, customize and enhance it. This shows a separation of concerns where theme is a base and plugin an extension. Sharing any functionality between the two is a bad practice because it creates coupling in the system which hinders portability and maintainability of the code.
So should you just duplicate and repeat the code? No. Use theme as a standalone base and create plugins to extend its functionality, don’t repeat it in both places. There is a concept of “plugin territory” – things that should be implemented not inside theme but as custom plugins, you can read more about it here.
Ideally, your plugins should extend just the WP core functionality but for bigger projects, it’s common practice to create plugins designed for a specific theme. But even then you should design the plugin in the most “independent” way so when you switch the theme, implementing plugin’s functionality would be very simple. And of course, you should make any functionality that depends on one another conditional. Check if the plugin is active if you must implement its config or functionality inside your theme and not somewhere in the admin UI.