How do you target virtual pages in code?

The WordPress, just like any other CMS, relies on generating content based on the user’s request and then outputting it to the browser as an HTML page. What you asked can have a very long answer, but here is a simple explanation to what you asked.

We begin with the file named .htaccess, which is a server file. This is what is inside an .htaccess file ( that is generated by WordPress when you activate pretty permalinks):

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

The code simply tells the server to:

If the requested URL is not a file or directory, then send the request to index.php, which is the place when WordPress is told what to load and view.

When you are trying to access a post’s content, for example by visiting http://example.com/my-category/my-first-post, WordPress checks the URL and notices that you have tried to access a single post’s content. It then will try and generate the content for that particular page.

Every page in WordPress has it’s own template, which is like a blank form that is going to be filled with data. For example, the template file for a single post, is called single.php and is located in the root of your templates directory. So, when you try to visit a post, the code inside that template part will be run.

To have a better understanding of templates hierarchy, take a look into the below picture:

WordPress template hierarchy

So, how do we target these pages? The first approach is to find the proper template file and directly edit it. This is not recommended as the template file may be overridden in the future by updates.

Another approach is to find the proper hook to change what we need to change. For example if you want to change the WordPress’s title, you can hook into wp_title hook:

add_filter( 'wp_title', 'my_wp_title', 10, 2 );
function my_wp_title(){
    return 'Hello!';
}

This will set the title of your WordPress to Hello!. As i mentioned, your question is broad and the answer to it can be very long. If you exactly specify your problem, i can post a more accurate answer.

I hope this helped you out with understanding of how WordPress (or any other CMS) renders it’s content.