0

I am trying to check if a certain archive file template exists in the WP theme directory. This is my code, I am not sure what I am missing here.

<?php 

$file_name = '/archive.php';
$base_template_dir = get_template_directory_uri();

$file_uri = $base_template_dir.$file_name;
$file_uri = str_replace('http://', '', $file_uri);
$file_uri = str_replace('https://', '', $file_uri);

$file_uri = str_replace($_SERVER['HTTP_HOST'], '', $file_uri);

if (file_exists($file_uri)) {
    echo 'File Found: '.$file_uri;
} else {
    echo 'File Not Found: '.$file_uri;
}
?>
5
  • The WP root directory or the theme directory? Commented May 13, 2022 at 7:07
  • 1
    What is $mPath? I don't see it defined anywhere in your code.
    – Sally CJ
    Commented May 13, 2022 at 7:09
  • @JacobPeattie, that was a Typo.. I meant the theme directory
    – Tamara
    Commented May 13, 2022 at 9:03
  • @SallyCJ that was a typo… it has been corrected to reflect the $file_uri variable – However, the code still doesn't work even though i have an archive.php file available in the theme's directory
    – Tamara
    Commented May 13, 2022 at 9:30
  • Yes @Tamara, I knew $file_uri wouldn't work, and I was only telling you that you've used an undefined variable.
    – Sally CJ
    Commented May 13, 2022 at 9:55

1 Answer 1

1

Most of this code is unnecessary. You're attempting to convert a URL to a path when you could just use the function that returns a path.

$path = get_theme_file_path( 'archive.php' );

if ( file_exists( $path ) ) {
    echo 'File Found: '. $path;
} else {
    echo 'File Not Found: '. $path;
}
1
  • Thanks, get_template_directory_uri() was the wrong function to start with. get_theme_file_path() worked perfectly
    – Tamara
    Commented May 13, 2022 at 10:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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