‘POST’,
‘permission_callback’ => ‘__return_true’,
‘callback’ => function (WP_REST_Request $req) {
$email = sanitize_email((string) $req->get_param(’email’));
if (!is_email($email)) {
return new WP_REST_Response(array(‘ok’ => false, ‘error’ => ‘invalid_email’), 400);
}
$to = ‘gareth@digitalmarketingfirst.co.uk’;
$subject = ‘New free marketing audit request — digitalmarketingfirst.co.uk’;
$body = “A visitor requested a free marketing audit.\n\n”
. “Email: {$email}\n”
. “Time: ” . current_time(‘mysql’) . “\n”
. “Page: ” . home_url(‘/dmf-home-preview/’) . “\n”;
$headers = array(
‘Content-Type: text/plain; charset=UTF-8’,
‘Reply-To: ‘ . $email,
);
$sent = wp_mail($to, $subject, $body, $headers);
return new WP_REST_Response(array(‘ok’ => (bool) $sent), $sent ? 200 : 500);
},
));
});

add_action(‘template_redirect’, function () {
$path = trim((string) parse_url($_SERVER[‘REQUEST_URI’], PHP_URL_PATH), ‘/’);
$is_preview = ($path === ‘dmf-home-preview’);
$is_home = is_front_page(); // WordPress front page detection
if (!$is_preview && !$is_home) {
return;
}

$uploads = wp_upload_dir();
$file = trailingslashit($uploads[‘basedir’]) . ‘dmf-home/home.html’;

if (!file_exists($file)) {
// Never break the live homepage if the asset is missing — fall back to WP.
if ($is_home) { return; }
status_header(404);
nocache_headers();
echo ‘DMF preview not found: wp-content/uploads/dmf-home/home.html is missing.’;
exit;
}

$base = untrailingslashit($uploads[‘baseurl’]) . ‘/dmf-home’;
$html = str_replace(‘{{ASSET_BASE}}’, $base, (string) file_get_contents($file));

nocache_headers();
status_header(200);
header(‘Content-Type: text/html; charset=utf-8’);
if ($is_preview) {
// Preview stays out of search; the live homepage is left indexable.
header(‘X-Robots-Tag: noindex, nofollow’, true);
}
echo $html;
exit;
}, 1);

LOADER;
file_put_contents($target, $content);
error_log(‘Updated: ‘ . $target);
?>