plugins - Why does my file_exist check fail?

admin2025-06-04  1

So basically, I'm trying to check if the user wants to overwrite my plugin template in his theme.

I have a plugin with a Custom Post Type 'links'. According to WP template system my archive file is 'archive-links.php'.

So, why does my check for the file 'archive-links.php' in the template folder always return false?

if(is_post_type_archive('links')) {

    $file = get_template_directory_uri() . '/archive-links.php';

    if(file_exists($file)) {
        // echo('working');
        // template overwrite
        return get_template_directory_uri() . '/archive-links.php';
    } else {
        // echo('not working');
        // default plugin archive file
        return plugin_dir_path(__DIR__) . 'templates/archive-links.php';
    }
}

So basically, I'm trying to check if the user wants to overwrite my plugin template in his theme.

I have a plugin with a Custom Post Type 'links'. According to WP template system my archive file is 'archive-links.php'.

So, why does my check for the file 'archive-links.php' in the template folder always return false?

if(is_post_type_archive('links')) {

    $file = get_template_directory_uri() . '/archive-links.php';

    if(file_exists($file)) {
        // echo('working');
        // template overwrite
        return get_template_directory_uri() . '/archive-links.php';
    } else {
        // echo('not working');
        // default plugin archive file
        return plugin_dir_path(__DIR__) . 'templates/archive-links.php';
    }
}
Share Improve this question asked Jan 18, 2019 at 2:01 user3135691user3135691 1,0359 silver badges15 bronze badges 2
  • Which file is that code located in? Is it in the main folder of your plugin? Can you expand your code block to include the entire function? I'm assuming this is a filter but the add_filter call is missing as is the function name etc – Tom J Nowell Commented Jan 18, 2019 at 2:18
  • 1 Possible duplicate of file_exists() acting weird – Jacob Peattie Commented Jan 18, 2019 at 3:23
Add a comment  | 

1 Answer 1

Reset to default 2

get_template_directory_uri doesn't return the directory name, it returns the URL of the directory. file_exists needs a file path, not a file URL.

Use get_template_directory instead, and don't forget to check get_stylesheet_directory too for those using child themes

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748999544a315500.html

最新回复(0)