Using Laravel routes to replace /

Is it possible to replace the homepage with a Laravel route? It technically works now, but won’t respect functionality like searching via /?q=...

eg,

routes/web.php

Route::get('/', function () {
    return view('landing');
});

…some funny side effects, it wipes out a lot of /wp/wp-admin/

I’m not sure if there are other unintended side effects to wrapping the route in a conditional, but you could prevent the route from loading if is_admin() is true.

For the search functionality, you could check for the existence of the search parameter and return the search view.

Not all of the standard WP globals, including $wp_query and $wp_admin_bar, are initialized automatically, so you’ll need to set those manually. If you need other globals that also aren’t being initialized, you could set those here as well.

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

if (! is_admin()) {
    Route::get('/', function (Request $request) {
        if ($request->query('s') !== null) {
            // This function is private within WP and not intended for non-internal use,
            // but you can see how WP loads it for example.
            // https://developer.wordpress.org/reference/functions/_wp_admin_bar_init/
            _wp_admin_bar_init();

            // Set $wp_query and related globals.
            global $wp;
            global $wp_query;
            $wp_query = new WP_Query($request->getQueryString());
            $wp->register_globals();
            return view('search');
        }

        return view('landing');
    });
}
2 Likes