I've been experimenting with repurposing WordPress's 404 handler/template file for a Real Estate site that I'm developing. I understand that when a non-existent URL is requested, the 404 page gets served up and that it returns a 404 status code (instead of a 200). But I've recently found a way to adapt the 404 template file so that it does something a bit more creative. More specifically, I'm first parsing the non-existent URL that was requested, and then using the returned value to query an external API and then display the returned data. So far it's working much better than I'd expected, though I'm aware of one significant issue that I'm hoping I can address.
In those situations where the 404 handler is served up, yet data is returned from querying the external API, .. how can I then -- and only then -- re-write the "404" header information so that it's a "200" status code? I ask because I don't want these "Page Not Found" entries littering our Google Analytics reports and mucking up the site's SEO ranking.
Here is an example non-existent URL which triggers the serving up of the 404 handler:
https://example.com/property/123-four-street/
I am parsing this URL using the following PHP code snippet:
$url = $_SERVER['REQUEST_URI'];
$path_parts = explode('/', $url);
$address = $path_parts[2];
$parsedaddress = str_replace("-", " ", $address);
echo $parsedaddress;
The "parsedaddress" value is then used to query the external API, and what I'd then like to have happen logic-wise is something along the lines of ...
if (query returns valid MLS data)
then (force a "200" status code and display the MLS data)
else (retain the "404" status code and display the 404 error page)
I've already added this custom function to my functions.php file, which is successfully changing the default page title for the 404 handler ... so I know that I can hook in to it. But how might I adapt this so that it conditionally rewrites the header information?
function theme_slug_filter_wp_title( $title_parts ) {
if ( is_404() ) {
$url = $_SERVER['REQUEST_URI'];
$path_parts = explode('/', $url);
$address = $path_parts[2];
$parsedaddress = str_replace("-", " ", $address);
$title_parts['title'] = ucwords($parsedaddress) . ' | AAA Real Estate;
}
return $title_parts;
}
add_filter( 'document_title_parts', 'theme_slug_filter_wp_title' );
Any help or advice would be appreciated.
Thanks, -- Yvan