1

I'm currently using a custom child theme across multiple sites, and would like to modularise particular custom features (e.g. ecommerce) by separating them into individual php files, and including the relevant ones as needed (without making them into plugins), since otherwise it's difficult to keep track of the customisations in each file across multiple variations of the child theme.

To do this, I'd like to be able to copy particular php files into a folder in the child theme, and for these to be included automatically. How would I achieve this?I've tried several solutions, but they don't seem to work in this context. Here's an example of a code I used:

function include_all_php($folder){
 foreach (glob("{$folder}/*.php") as $filename)
 {
    include $filename;
 }
}
include_all_php("includes"); // "includes" is the name of the folder in the child theme
6
  • Move the shared files to plugins or libraries, and learn how to use an auto-loader. – fuxia May 27 '16 at 2:21
  • Include the actual code you have tried if it is different to the linked solution. – majick May 27 '16 at 6:45
  • @majick OK, I've included an example of the code I tried. – Tim May 29 '16 at 3:28
  • @bosco That's what I'm here to find out. Please see the new code example above. – Tim May 29 '16 at 3:42
  • @toscho Could you suggest some resources for looking into those? Thanks. – Tim May 29 '16 at 3:43
0

I suspect glob needs the current working directory to work, so you could try passing the full path of the file to the existing function you have...

include_all_php(dirname(__FILE__).'/includes');

Or set the current working directory first:

setcwd(dirname(__FILE__).'/');
include_all_php('includes');

Alternatively you could also use scandir:

$filepath = dirname(__FILE__).'/includes/';
$files = scandir($filepath);
foreach ($files as $file) {
    // match the file extension to .php
    if (substr($file,-4,4) == '.php') {include($filepath.$file);}
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.