Hi everyone,
I am trying to initialize the slim framework inside a WordPress plugin, but I keep getting Slim\Exception\HttpNotFoundException (404) Not found
. error when I visit the /slim-endpoint/
url.
(I have confirmed and the rewrite_rules contains the correct rewrites)
Can anyone look at this code and suggest anything?
init-slim.php
<?php
defined('WPINC') || die;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;
function wpsf_init_slim() {
// Create Slim app instance
$app = AppFactory::create();
// Include route files
$routes = __DIR__ . '/routes/*.route.php';
$routes = glob($routes);
foreach ($routes as $route) {
include_once $route;
}
// Handle the current request
$app->run();
}
function wpsf_add_rewrite_rules() {
add_rewrite_rule('^slim-endpoint/?$', 'index.php?slim_route=slim-endpoint', 'top');
add_rewrite_rule('^another-endpoint/?$', 'index.php?slim_route=another-endpoint', 'top');
}
function wpsf_flush_rewrite_rules() {
wpsf_add_rewrite_rules();
flush_rewrite_rules();
}
function wpsf_query_vars($vars) {
$vars[] = 'slim_route';
return $vars;
}
function wpsf_template_redirect() {
global $wp_query;
// Debugging output
if (isset($wp_query->query_vars['slim_route'])) {
error_log('Slim route detected in query_vars: ' . $wp_query->query_vars['slim_route']);
wpsf_init_slim();
exit; // Stop further execution if Slim route matched
} else {
error_log('Slim route not found in query_vars');
}
}
add_filter('query_vars', 'wpsf_query_vars');
add_action('template_redirect', 'wpsf_template_redirect');
add_action('init', 'wpsf_add_rewrite_rules');
register_activation_hook(__FILE__, 'wpsf_flush_rewrite_rules');
./routes/test.route.php
<?php
defined('WPINC') || die;
// Define routes
$app->get('/slim-endpoint', function (Request $request, Response $response, $args) {
$response->getBody()->write("Hello from Slim!");
return $response;
});
$app->get('/another-endpoint', function (Request $request, Response $response, $args) {
$response->getBody()->write("This is another endpoint.");
return $response;
});
rewrite_rules
option value in database
Array
(
// other values
[^slim-endpoint/?$] => index.php?slim_route=slim-endpoint
[^another-endpoint/?$] => index.php?slim_route=another-endpoint
// other values
)