Brain-WP / Cortex

Routing system for WordPress
MIT License
348 stars 20 forks source link

[Question] could you describe how to do a paginated route? #21

Closed jonathanstegall closed 6 years ago

jonathanstegall commented 6 years ago

I'm finding this difficult to understand. In /brain/cortex/src/Cortex/Route/PriorityRouteCollection.php, I notice this code:

private function maybeBuildPaged(RouteInterface $route)
{
    $built = null;
    $pagedArg = $route->offsetExists('paged') ? $route->offsetGet('paged') : '';
    $path = $route->offsetExists('path') ? $route->offsetGet('path') : '';
    if (in_array($pagedArg, self::$pagedFlags, true) && $path && is_string($path)) {
        $base = 'page';
        /** @var \WP_Rewrite $wp_rewrite */
        global $wp_rewrite;
        $wp_rewrite instanceof \WP_Rewrite and $base = $wp_rewrite->pagination_base;
        $array = $route->toArray();
        $array['id'] = $route->id().'_paged';
        $array['paged'] = RouteInterface::PAGED_UNPAGED;
        $array['path'] = $pagedArg === RouteInterface::PAGED_ARCHIVE
            ? $path.'/'.$base.'/{paged:\d+}'
            : $path.'/{page:\d+}';

        $routeVars = $route->offsetExists('vars') ? $route->offsetGet('vars') : [];
        if (is_callable($routeVars)) {
            $array['vars'] = $this->buildPagedVars($routeVars, $pagedArg);
        }

        $built = apply_filters('cortex.paged-route', new Route($array), $route);
    }

    return $built;
}

My route is like this:

$routes->addRoute( new QueryRoute(
    $title,
    $query,
    [
        'paged' => true,
        'template' => 'my-template.php',
    ]
));

I've tried changing the paged value between true, 1, and the page number that I want to use (ex 2), but so far I am only able to get the first page of the paginated query to run.

In other words, /my-spill/ works, and it loads the first 10 posts from $query as it should, but /my-spill/page/2/ returns my theme's 404 page.

jonathanstegall commented 6 years ago

Actually I think I figured this out, reading more about FastRoute. Here's what is working for me:

$routes->addRoute( new QueryRoute(
    $title . '[/page/{page:\d+}]',
    $query,
    [
        'paged' => true,
        'template' => 'my-template.php',
    ]
));

With this, /my-spill/ works, and also /my-spill/page/2.