Giter VIP home page Giter VIP logo

routes's Introduction

Routes

Simple routing for WordPress. Designed for usage with Timber

Build Status Coverage Status Packagist Downloads

Basic Usage

/* functions.php */
Routes::map('myfoo/bar', 'my_callback_function');
Routes::map('my-events/:event', function($params) {
    $event_slug = $params['event'];
    $event = new ECP_Event($event_slug);
    $query = new WPQuery(); //if you want to send a custom query to the page's main loop
    Routes::load('single.php', array('event' => $event), $query, 200);
});

Using routes makes it easy for you to implement custom pagination — and anything else you might imagine in your wildest dreams of URLs and parameters. OMG so easy!

Some examples

In your functions.php file, this can be called anywhere (don't hook it to init or another action or it might be called too late)

<?php
Routes::map('blog/:name', function($params){
    $query = 'posts_per_page=3&post_type='.$params['name'];
    Routes::load('archive.php', null, $query, 200);
});

Routes::map('blog/:name/page/:pg', function($params){
    $query = 'posts_per_page=3&post_type='.$params['name'].'&paged='.$params['pg'];
    $params = array('thing' => 'foo', 'bar' => 'I dont even know');
    Routes::load('archive.php', $params, $query);
});

map

Routes::map($pattern, $callback)

Usage

A functions.php where I want to display custom paginated content:

<?php
Routes::map('info/:name/page/:pg', function($params){
	//make a custom query based on incoming path and run it...
	$query = 'posts_per_page=3&post_type='.$params['name'].'&paged='.intval($params['pg']);

	//load up a template which will use that query
	Routes::load('archive.php', null, $query);
});

Arguments

$pattern (required) Set a pattern for Routes to match on, by default everything is handled as a string. Any segment that begins with a : is handled as a variable, for example:

To paginate:

page/:pagenum

To edit a user:

my-users/:userid/edit

$callback A function that should fire when the pattern matches the request. Callback takes one argument which is an array of the parameters passed in the URL.

So in this example: 'info/:name/page/:pg', $params would have data for:

  • $data['name']
  • $data['pg']

... which you can use in the callback function as a part of your query


load

Routes::load($php_file, $args, $query = null, $status_code = 200)

Arguments

$php_file (required) A PHP file to load, in my experience this is usually your archive.php or a generic listing page (but don't worry it can be anything!)

$template_params Any data you want to send to the resulting view. Example:

<?php
/* functions.php */

Routes::map('info/:name/page/:pg', function($params){
    //make a custom query based on incoming path and run it...
    $query = 'posts_per_page=3&post_type='.$params['name'].'&paged='.intval($params['pg']);

    //load up a template which will use that query
    $params['my_title'] = 'This is my custom title';
    Routes::load('archive.php', $params, $query, 200);
});
<?php
/* archive.php */

global $params;
$context['wp_title'] = $params['my_title']; // "This is my custom title"
/* the rest as normal... */
Timber::render('archive.twig', $context);

$query The query you want to use, it can accept a string or array just like Timber::get_posts -- use the standard WP_Query syntax (or a WP_Query object too)

$status_code Send an optional status code. Defaults to 200 for 'Success/OK'

routes's People

Contributors

adamtomat avatar athomasraka avatar azeemhassni avatar daronspence avatar idflood avatar jarednova avatar jmayhak avatar nlemoine avatar parisholley avatar peterkracik avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

routes's Issues

Fatal error in WordPress 4.6

WordPress 4.6 now includes Ryan McCue's Requests Library.

When using Routes it is possible to get a Fatal Error as you are also including this Library but in an older version it would seem? Anyway, The Request_Response Classes aren't the same. Yours is getting used in preference to the included one. This causes the is_redirect() method to be reported as missing and WP has a fatal crash.

Fix in the meantime is to just delete the Requests Folder in vendor

Query parameter not working with Wordpress 6

Hi, after updating Wordpress to 6 we noticed that the $query parameter is not working anymore.

Routes::map('some-test-page', function($params){
  $query = ['post_type' => 'custom-type'];
  Routes::load('my-template.php', $params, $query);
});

In the file my-template we were using something like $posts = (array) new Timber\PostQuery(); which was using this $query but it's not the case anymore.

README for custom WP_Query is incorrect

I defined the following route:

Routes::map('category/:category/:subcategory', function($params) {
    $category = $params['category'];
    $subcategory = $params['subcategory'];
    $query = new \WP_Query(array(
        'post_type' => 'post',
        'category_name' => $category,
        'tax_query' => array(
            array(
                'taxonomy' => 'secondary_category',
                'field'    => 'slug',
                'terms'    => $subcategory,
            ),
        ),
    ));
    Routes::load('archive.php', array('category' => $category, 'subcategory' => $subcategory), $query);
});

But I get the error:

Warning: parse_str() expects parameter 1 to be string, object given in /upstatement/routes/Routes.php on line 139

In fact you just need to pass the arguments array, not a WP_Query object:

Routes::map('category/:category/:subcategory', function($params) {
    $category = $params['category'];
    $subcategory = $params['subcategory'];
    $query = array(
        'post_type' => 'post',
        'category_name' => $category,
        'tax_query' => array(
            array(
                'taxonomy' => 'secondary_category',
                'field'    => 'slug',
                'terms'    => $subcategory,
            ),
        ),
    );
    Routes::load('archive.php', array('category' => $category, 'subcategory' => $subcategory), $query);
});

Make more (all?) AltoRouter options available

AltoRouter already provides optional parameters, but Timber doesn't support them because this router strips question marks. I would like to use optional parameters, and maybe it wouldn't be a bad idea to just provide access to the AltoRouter object?

Something like

Routes::getRouter()->addRoutes([
['GET','/users/[i:id?]', function($params) {
etc...
})

Custom Route with RSS Feed

Hi guys, I've been trying to get a custom route for a custom archive page to work with a RSS feed.

The page itself works great with pagination etc. Only the feed doesn't exist.

Here is some sample code:

    // create CPT (x 3)
    register_post_type($name, array(
      'label' => 'custom1',
      'public' => true,
      'capability_type' => 'page',
      'supports' => array( 'title', 'author', 'excerpt', 'revisions', 'thumbnail'),
      'taxonomies' => array('post_tag'),
      'has_archive' => true
    ));

    // CPT route
    Routes::map('test/filter/:filter', function($params){
        $query = array(
          'post_type' => array('custom1', 'custom2', 'custom3' )
        );
        $filter = $params;
        Routes::load('archive.php', $filter, $query, 200);
    });

    // paging CPT route
    Routes::map('test/filter/:filter/page/:page', function($params){
        $query = array(
          'post_type' => array('custom1', 'custom2', 'custom3' ),
          'paged' => intval($params['page'])
        );
        $filter = $params;
        Routes::load('archive.php', $filter, $query, 200);
     });

I'm wondering if I need to create the feed itself as I'm not sure the Route method does it. {url}/feed is not found.

I've also tried creating a new WP_query but that only creates an error on line 140 of Routes.php

// CPT route
    Routes::map('test/filter/:filter', function($params){
        $query = array(
          'post_type' => array('custom1', 'custom2', 'custom3' )
        );
        $filter = $params;
        Routes::load('archive.php', $filter, $query, 200);
    });

Any help is much appreciated. (Also I think the readme might be out dated)

Library PHP Compatibility PHP 8.x

Hi all,

customer on our end uses this library in its theme. Currenty we try migrating the whole theme to PHP 8.2 but could not find any information if this plugin will work with PHP 8.2. On packagist it currently states the following PHP compatibility:

php: >=5.6.0|7.*

This currently looks like its not compatible. If not, is there any plan to migrate this library to PHP 8.2 and if yes, when can we expect an updated version?

Thanks in advance & sorry if this question is not suitable for the issues here.

Bad phpdoc

I think there is an error with the documentation of the function Routes::load(...)

* @param array $template           A php file to load (ex: 'single.php')
* @param array|bool $tparams       An array of data to send to the php file. Inside the php file
...

The $template variable is not I think of type array but of type string, so the phpdoc must be :

* @param string $template           A php file to load (ex: 'single.php')
* @param array|bool $tparams     An array of data to send to the php file. Inside the php file
...

I have this error : Expected parameter of type 'array', 'string' provided :(

Capture d’écran du 2021-04-19 00-59-13

Routes::load() loads index.php file instead of defined file

I have the following routes in my functions.php:


// Create initial worldmap
Routes::map('verzeichnis', function() {
    Routes::load(get_stylesheet_directory() . '/directory/directory.php', null, null, 200);
});
// Create fixated slugstructure
Routes::map('verzeichnis/:country', function($params) {
    $query = 'posts_per_page=30&country='.$params['country'];
    Routes::load(get_stylesheet_directory() . '/directory/directory-country.php', $params, $query, 200);
});

Routes::map('verzeichnis/:country/:city', function($params) {
    $query = 'posts_per_page=30&country='.$params['country'].'&city='.$params['city'];
    Routes::load('directory/directory-city.php', $params, $query, 200);
});

Routes::map('verzeichnis/:country/:city/:rechtsgebiet', function($params) {
    $query = 'posts_per_page=30&country='.$params['country'].'&city='.$params['city'].'&rechtsgebiet='.$params['rechtsgebiet'];
    Routes::load('directory/directory-schwerpunkt.php', null, $query, 200);
});

According to the documentation everything should work fine and I can load the initial Route 'verzeichnis' - but as soon as I try to load one of the sub-routes I get the default behaviour of the index.php which shows my posts.

What I am wondering is if it would be possible to define a single dynamic route eg.

Routes::map('verzeichnis/:country/:city/:rechtsgebiet', fn()); 

where the parameters that are here dynamic are optional but not necessary.

Please update the documentation and or let me know where I could find some sort of support if this is not the right place. Thanks in advance!

PHP Warning: Creating default object from empty value

PHP version 7.2.29

Trace

wp-content/vendor/upstatement/routes/Routes.php:129
Routes::{closure}()
wp-includes/class-wp-hook.php:288
do_action('template_redirect')
wp-includes/template-loader.php:13

Looks like there is a reliance on this behavior. I'm not sure if it will be removed in a future version of PHP but there probably shouldn't be a reliance on it? 😄

Thoughts?

AltoRouter version limitation

Our application has a requirement of AltoRouter at version 1.2.0, however, this package is limiting the version to 1.1.0.

We're using Timber, which is including Upstatement/routes, and it's in WordPress where we have that higher dependancy on AltoRouter - because we are using our own routing package.

Suggested fix

I suggest we allow any version < 2.0.0, and I have added a pull request for this fix.

Image instead of the page

I'm having trouble with certain links.

if the url contains same word as an image within wordpress media, the router will redirect me to the image url.

for example:
the link mysite.com/category/books/ where "books" is a slug of the category, it should redirect me to the detail page of the category.
except there is an image "Books.jpg" within the wp media, in that case it will redirect me to the
mysite.com/wp-content/uploads/2018/09/Books.jpg.

as soon as I remove or rename the image, it works as it supposes to.

if I debug variables, everything's fine before the call Routes::load()

Second route callback dont work in similar routes

I have routes:
"/flight/:city/:country" - From city to country
"/flight/:country/:city" - From country to city
On callback i check params and do somthing or nothing.

Second route callback dont work.

ability to change HTTP status code within load() method?

Example:

Add to functions.php:

Routes::map('hello/world', function( $params ) {
	Routes::load('hello-world.php');
});

hello-world.php:

<?php
http_response_code(502);
die('hello world');

The browser shows a 200 response code, not a 502 as attempted within the route (hello-world.php). Obviously the Routes::load() method throws a 200 by default (which can be changed by passing a different code as the fourth parameter), but I'm wondering - is there a way that I can customize the status code within the loaded route?

typo in description

Hello,

there is a small typo in description
on the end is written

<?php
/* functions.php */

Routes::map('info/:name/page/:pg', function($params){
    //make a custom query based on incoming path and run it...
    $query = 'posts_per_page=3&post_type='.$params['name'].'&paged='.intval($params['pg']);

    //load up a template which will use that query
    $params = array();
    $params['my_title'] = 'This is my custom title';
    Routes::load('archive.php', $params, $query, 200);
});

what you do with "$params = array();" is that you are unnecessarily wiping out the $params value from the function context. In this case we we loose the "$params['pg']" and other data.

when WPML uses GET param as lang format

Wordpress 4.9.1 (multisite)
Timber 1.5.2

When WPML language URL format is "Language name added as a parameter" there is issue with calculating base_path in method Routes::map(). Function get_bloginfo('url') returns URL containg "?lang=en" which ends up with wrong base_path (I am not sure but maybe this is bug beacuse of multisite)

Fix on forked github repo:
https://github.com/luzel/routes

Load another page from argument

Hey everyone!

Is it possible to load domain.com/invite?referal=X from typing domain.com/invite/X/?

The only way I got it to work right now is by redirecting ("Location: domain.com/invite?referal=$params["X"]" and exit), the problem is that it is unnecesarily slow and user sees blank page for twice as much time.

Thank you.
Matej

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.