This is because you did not put singular.php
in the URL, and if you did it wouldn’t make any sense. Remember, WordPress loads the template, not the other way round, your mental model of how this works is upside down.
What’s going on? Why is singular.php the file being accessed while PHP prints that the current filename is /index.php?
Because the entry point to WordPress is index.php
in the root. index.php
then loads WordPress, and starts up the CMS for that request. It’ll look at your URL, convert it into arguments for fetching stuff from the database, then it grabs them. Then, it goes through a list of rules to figure out how to display that content, and picks a template file from your theme. So by the time it goes to load singular.php
it already knows which posts there are. singular.php
doesn’t make it display a single post, it’s the other way around, displaying a single post makes it load singular.php
.
Since $_SERVER["PHP_SELF"]
refers to the PHP file that was loaded by the server to handle the request, not the current file it is being run in, it will return index.php
.
How does WordPress know that it should load singular.php (& not any other php file)? I looked at page & I even don’t read this line at all:
Your server does not load singular.php
, WordPress does. singular.php
is just a PHP file that’s meant to display a singular post. Take a look at the template hierarchy for the full flow diagram of WordPress decides which template to load to display what it fetched from the database.
Another way to think of the misunderstanding is this:
When somebody writes on a piece of paper, how does the ink know to put the words in the persons head? And why does it say the person not the paper when I ask who the author is?
Clearly that doesn’t make sense when put in more familiar terms