0

I'm running some functions that will allow a user to register their own custom templates to my custom theme from an external directory. They can see these page templates in the wp-admin and they render on the frontend.

Everything works fine with this, but I would like to register files from multiple directories, not just one directory.

I need to make $file equal multiple directories. I've tried an array. I've tried && and a couple other things, including the below code, but nothing works.

I'm not a pro, but what am I missing here? Can this be done? In the code below I see that the last $file = takes priority over the previous $file =.

So is there a way I can make $file equals multiple paths?

In short, I want $file to consider multiple paths.

The code probably explains itself what I am trying to achieve.

    $file = CUSTOM_OPTION_BACKEND_TEMPLATES_PATH .      '/home/'            . get_post_meta( $post->ID, '_wp_page_template', true );
    $file = CUSTOM_OPTION_BACKEND_TEMPLATES_PATH .      '/pages/'           . get_post_meta( $post->ID, '_wp_page_template', true );
    $file = CUSTOM_OPTION_BACKEND_TEMPLATES_PATH .      '/blog/'            . get_post_meta( $post->ID, '_wp_page_template', true );
    $file = CUSTOM_OPTION_BACKEND_TEMPLATES_PATH .      '/single-posts/'    . get_post_meta( $post->ID, '_wp_page_template', true );
    $file = CUSTOM_OPTION_BACKEND_TEMPLATES_PATH .      '/products/'        . get_post_meta( $post->ID, '_wp_page_template', true );
    $file = CUSTOM_OPTION_BACKEND_TEMPLATES_PATH .      '/templates/'       . get_post_meta( $post->ID, '_wp_page_template', true );
    $file = CUSTOM_OPTION_BACKEND_TEMPLATES_PATH .      '/products/'        . get_post_meta( $post->ID, '_wp_page_template', true );


if ( file_exists( $file ) ) {
    return $file;
} 
0

the last $file takes priority over the previous

That's because you assign the new value to the $file variable at every line.

The only way I see you can do it by using the array:

<?php
// define directory list
$directories = array(
    'home',
    'pages',
    'blog',
    'single-posts',
    'products',
    'templates',
    'products'
);
// run through directories and return the result for each of them
foreach($directories as $directory) {
    // create path for each directory
    $path = CUSTOM_OPTION_BACKEND_TEMPLATES_PATH . '/' . $directory . '/' . get_post_meta( $post->ID, '_wp_page_template', true );
    // return path if file exists
    if ( file_exists( $path ) )
        return $path;
}
  • Thanks! This works. I'm not very familiar with the php options, just some, so the foreach is new to me to actually use. But now I get what it is doing in this case so I can have it in mind for the future. Appreciate it @MaxYudin – Fearless Mode Feb 9 '16 at 14:29

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.