Code Monkey home page Code Monkey logo

cortex's Introduction

Cortex

Travis CI codecov.io MIT license


Cortex is routing system for WordPress based on FastRoute

Start using Cortex

First of all ensure Composer autoload is loaded.

After that "boot" Cortex:

Brain\Cortex::boot();

This can be done as soon as you can, no need to wrap in a hook.

It will not work after 'do_parse_request' has been fired.

Adding routes

To add routes, it is possible to use 'cortex.routes' hook, that passes an instance of RouteCollectionInterface:

use Brain\Cortex\Route\RouteCollectionInterface;
use Brain\Cortex\Route\QueryRoute;

add_action('cortex.routes', function(RouteCollectionInterface $routes) {
	
	$routes->addRoute(new QueryRoute(
		'{type:[a-z]+}/latest',
		function(array $matches) {
		  return [
		    'post_type'      => $matches['type'],
		    'posts_per_page' => 5,
		    'orderby'        => 'date',
		    'order'          => 'ASC'
		  ];
		}
	));
});

The route pattern (1st argument) syntax is inherited from FastRoute.

The callback passed as second argument receives the array of matches ($routeInfo[2] in FastRoute) and has to return an array of arguments for WP_Query.

QueryRoute arguments

QueryRoute constructor accepts as 3rd argument an array of options for route configuration.

One of them is "template" to force WordPress use a template when the route matches:

add_action('cortex.routes', function(RouteCollectionInterface $routes) {
	
	$routes->addRoute(new QueryRoute(
		'post/latest',
		function(array $matches) {
		  return [
		    'orderby'        => 'date',
		    'order'          => 'DESC'
		  ];
		},
		['template' => 'latest.php']
	));
});

As shown above,template argument can be a relative path to theme (or child theme) folder.

To use a template that resides outside theme folder, template argument need to be full absolute path to the template file to use.

There are other arguments, among them:

  • "before" and "after", that are callbacks run respectively before and after the callback that returns query arguments is called
  • "host" to make the route match only for specific host
  • "method" to make the route match only for specific HTTP method (e.g. POST or GET)
  • "scheme" to make the route match only for specific HTTP scheme (e.g. https or http)
  • "group" to use configuration from one or more "route groups"
  • "priority" to force the route evaluation in specific order (lower priority first)
  • "merge_query_string" to allow (default) or avoid url query string are merged as query argument to anything returned by route callback

Route groups

A route group is a way to share common settings among routes.

Before assign groups to routes, we need to add groups.

That can be done using 'cortex.groups' hook, that pass an instance of GroupCollectionInterface:

use Brain\Cortex\Route\RouteCollectionInterface;
use Brain\Cortex\Group\GroupCollectionInterface;
use Brain\Cortex\Route\QueryRoute;
use Brain\Cortex\Group\Group;

add_action('cortex.groups', function(GroupCollectionInterface $groups) {
	
	$groups->addGroup(new Group([
	    'id'       => 'archive-group',
	    'template' => 'archive.php',
	    'before'   => function() {
	       // do something before route callback
	    }
	]));
});

add_action('cortex.routes', function(RouteCollectionInterface $routes) {
	
	$routes->addRoute(new QueryRoute(
	    '^post/latest$',
	    function(array $matches) {
	        return [
	            'orderby'        => 'date',
	            'order'          => 'DESC'
	        ];
	    },
	    ['group' => 'archive-group']
	));
	
	$routes->addRoute(new QueryRoute(
	    'post/oldest',
	    function(array $matches) {
	        return [
	            'orderby'        => 'date',
	            'order'          => 'ASC'
	         ];
	     },
	     ['group' => 'archive-group']
	));
});

A group is instantiated passing an array of values to its constructor. The value "id" is required. All other values are optional, and can be used to set any route property (array items in 3rd param of QueryRoute constructor).

To use properties from a group in a route, the group id has to be set in the 'group' route property.

'group' property also accepts an array of group ids, to assign properties from multiple groups.

Redirect routes

QueryRoute is just one of the routes shipped with Cortex. There are others and it is possible to write custom routes implementing Brain\Cortex\Route\RouteInterface.

Another implementation included in Cortex is RedirectRoute. As the name suggests, it is used to redirect urls to other urls.

use Brain\Cortex\Route\RouteCollectionInterface;
use Brain\Cortex\Route\RedirectRoute;

add_action('cortex.routes', function(RouteCollectionInterface $routes) {
	
	$routes->addRoute(new RedirectRoute(
		'old/url/{postname}',
		function(array $matches) {
		  return 'new/url/' . $matches['postname'];
		}
	));
});

RedirectRoute accepts an array of options as well.

Using option is possible to configure HTTP status code to use ('redirect_status' option, default 302) and if allows or not redirect to external urls ('redirect_external' option, default false).


Installation

Via Composer, require brain/cortex in version ~1.0.0.

composer require brain/cortex:~1.0.0

You may need to lessen your project's minimum stability requirements.

composer config minimum-stability dev

Minimum Requirements

  • PHP 5.5+
  • Composer to install

Dependencies

  • Any version of PSR7 interfaces (no implementation required)
  • FastRoute

License

MIT

cortex's People

Contributors

audvin avatar gmazzap avatar metaline avatar polevaultweb avatar pongho avatar rtpharry avatar tfrommen 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

cortex's Issues

[Question] Is there any way to give Cortext routes a higher priority over WP routes?

Hey,

Firs of all - thanks for Cortex. It's a great tool! WP sucks, but with Cortex it suck a bit less ;P


I have a little problem and I'd like to know if the solution I came up with is the only solution, or maybe is there a better, simpler one.

I have a hierarchical taxonomy. Let's say it's a country/region/district hierarchy. So, among others, I will have the following routes:

  • mysite.com/{country}
  • mysite.com/{country}/{region}
  • mysite.com/{country}/{region}/{disctrict}

It looks very simple so far, but there's a little problem. Let's pick the first route: mysite.com/{country}. This URL structure looks the same a default WordPress URL for pages. So, in order to create such a route I do the following trick:

// Get all pages
$pages = new \WP_Query([
    'post_type' => 'page',
    'posts_per_page' => -1,
]);

// Get an array of all the slugs
$pagesSlugs = wp_list_pluck($pages->posts, 'post_name');

// Build a pipe separated string
$pagesSlugsPipeSeparated = implode('|',$pagesSlugs);

// Register a route. 
$routes->addRoute(new QueryRoute(
    '{country:(?!' . $pagesSlugsPipeSeparated . ')[a-z0-9-]+}', // Exclude all pages using regexp
    function (array $matches) {
        return [
            // My query args
        ];
    },
    [
        'template' => 'test-router.php'
    ]
));

So, I build routes using regexp and exclude all pages slugs from the route. I could do it in an opposite way - I could join all taxonomy terms - but this solution is un-performant because of a huge amount of taxonomy terms.

I'd like to avoid so complex regexp if possible.


So the question is: is it possible to make Cortex routes to have a higher priority over WordPress default routes? Basically, I'd like it to work like the WordPress add_rewrite_rule function when the $after parameter is set to top.

I know that I can disable WordPress rewrite rules and use Cortex for everything, but this is not a solution.

About template

Hi,

I have done a simple plugin that use Cortex as routing system.

My plugin produce an html string that I need to render into default template.

add_action('wp_loaded', function () {
    Cortex::boot();
    add_action('cortex.routes', function (Route\RouteCollectionInterface $routes) {
        $routes->addRoute(new Route\QueryRoute(
            '{code:[A-Z]+}/myTest',
            function (array $matches) {
                $myObj = new myObj();
                $html=myObj->getHtml($matches['code']);

/** how to render template with $html ? **/                

            }
        ));
    });
});

What are correct steps?

Thanks in advance.
v.

Current status for this project?

I'm just wondering what the current status for this project is.

I've been using it for some smaller and larger projects recently and I'm really starting to like it. The only drawback that I can see, is that this project still seems to be in alpha. From what I can tell, there are some undocumentet features (like the controllers), which makes me worried things might be changing.

Handle 404 error

Hello.
I have a question about handling 404 errors. For example, I have this setup:

add_action('cortex.groups', function(GroupCollectionInterface $groups) {
	$groups->addGroup(new Group(array(
	    'id'       => 'archive-custom-post-type',
	    'template' => 'archive-cpts.php',
	)));
});

add_action('cortex.routes', function(RouteCollectionInterface $routes) {
	$cpts = get_post_type_object( 'cpts' );
	$routes->addRoute(new QueryRoute(
		$cpts->has_archive . '/{meta_value:.+?}/',
		function(array $matches) {
		  return array(
			'post_type'      => 'cpts',
			'meta_key' => 'cpts_meta_key',
		        'meta_value' => $matches['meta_value'],
		  );
		},
		array(
			'group' => 'archive-custom-post-type'
		)
	));
});

When a custom post can't be found this still displays archive-cpts.php template instead of 404 page. I can see error404 class in body tag of the template though.
Did I miss something? Could you point it out, please?

[feature request] Closures as a value for the `template` setting

At the moment a template can take only a string as an argument. It would be great if we also could use a closures. The closure could take $matches and ideally s $wp_query (if it's available at this point) as an argument.

Example:

$routes->addRoute( new QueryRoute(
	'my/route/{param}',
	function ( array $matches ) {
		return [
			'post_type' => 'my_post_type',
		];
	},
	[
		'template' => function ( array $matches, \WP_Query $query ) {
			if ( $matches['param'] === 'something' && $query->post_count > 1 ) {
				return 'a-tempalte.php';
			}

			return 'another-template.php';
		}
	]
) );

Abandoned packages and Parse error | PHP 8.0.11

Package brain/amygdala is abandoned, you should avoid using it. No replacement was suggested.
Package brain/brain is abandoned, you should avoid using it. No replacement was suggested.
Package brain/striatum is abandoned, you should avoid using it. No replacement was suggested.
Package brain/support is abandoned, you should avoid using it. No replacement was suggested.
Package twig/cache-extension is abandoned, you should avoid using it. Use twig/cache-extra instead.

( ! ) Parse error: syntax error, unexpected token "" in /Users/andy/Documents/associationweb/web/app/themes/asweb/vendor/brain/support/src/Facade.php on line 34

Lost taxonomy term data using query()

I made this route to order posts by meta date-init.

Route::add('agenda/agenda_category/{tax}')
    ->methods(['GET'])
    ->requirements(['tax' => '[a-zA-Z0-9-_]{1,}'])
    ->query(function ($matches)
    {
        return [
            'post_type' => 'agenda',
            'orderby'   => 'meta_value_num',
            'order'     => 'ASC',
            'meta_key'  => 'date-init',
            'tax_query' => [
                [
                    'taxonomy' => 'agenda_category',
                    'field'    => 'name',
                    'terms'    => $matches['tax'],
                ]
            ]
        ];

    });

Without this route I can get the taxonomy term by get_query_var('term'), but with this route I can't.
Am I missing something? Changing the order of the global query shouldn't alter the global vars used by WordPress.

Composer could not be resolved to an installable set of packages. (Cortex-Plugin)

Hi Giuseppe.
A few days ago we talked about an issue I had and you said that it would be because of the minimum stability version.
At that time I installed Cortex plugin running composer in its own directory... and it works, but it is not the best solution because I need to run composer on my root project and where the Cortex plugin is.
So, if I try this on my composer:

"require": {
        "php": ">=5.4",
        "Giuseppe-Mazzapica/Cortex-Plugin" : "dev-master"
    },
    "minimum-stability" : "dev",
    "prefer-stable": true

I got the message:

Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - The requested package bruno-barros/cortex-plugin could not be found in any version, there may be a typo in the package name.

Potential causes:
 - A typo in the package name
 - The package is not available in a stable-enough version according to your minimum-stability setting
   see <https://groups.google.com/d/topic/composer-dev/_g3ASeIFlrc/discussion> for more details.

I really do not have a answer, but maybe you could promote a tag version to all the projects to avoid dev-master.

Simple example not fired.

I do this simple wp plugin file.

include __DIR__ . '/vendor/autoload.php';
function myplugin_wp_activate() {}
function myplugin_wp_deactivate(){}
register_activation_hook(__FILE__, 'myplugin_wp_activate');
register_deactivation_hook(__FILE__, 'myplugin_wp_deactivate');

use Brain\Cortex;
use Brain\Cortex\Route;

add_action('wp_loaded', function () {
    Cortex::boot();

    add_action('cortex.routes', function (Route\RouteCollectionInterface $routes) {

        $routes->addRoute(new Route\QueryRoute(
            '{code:[A-Z]+}/test',
            function (array $matches) {
                echo "here!";
                die;

                return [
                    'code' => $matches['code']
                ];
            }
        ));
    });
});

But when I try the url http://mydomain/MYCODE/test I don't get the "here!" text.
Where is my mistake?

v.

Accessing $matches within before or after callbacks

Hi there -

Really loving this library. Definitely the smoothest routing utility for WordPress that I've found!

I'm trying to figure out how to access the captured $matches within the before/after callbacks. Right now, as far as I can tell, you can only access it in the $queryBuilder callable.

It's very possible I'm missing something obvious… if not, consider this a feature request :)

Thanks!

Extra exmaples

Do you have any simple examples for changing the permalink structure for cpts?

I would like to get this structure but I am not sure it is possible? example.com/{cat}/{post_name}

Thank you.

Routes->url() lacks request context

Hello Guiseppe,

We're developing two websites build on top of one WordPress instance. Your routing component has been a great help in quickly and efficiently getting the routing right.

While using your component we found that there are some minor issues. The most important of these issues concerns the generation of urls based on the route ids. We use two different host for our two websites, but this contextual information is ignored when generating urls based on route ids.

Looking into the matter we found that the Symfony RequestContext is used as an empty shell. Normally this object is populated with information from the HttpFoundation Request object, but you also got your own Request object. Could you use either of these to populate RequestContext? Thanks!

Cheers,
Wouter van Dam

WPML and Cortex

Hello Guiseppe,

have you tried using Cortex's routing capabilities with a site that uses WPML for making it multilingual? I guess it won't really work out of the box. Do you think with route groups and and callback it would be manageable? Or in general how would you aproach a site with multiple languages? Multisites?

Boot Cortex

Hi Giuseppe.

I'm still on 0.1.0 just waiting your stable version.

Can I boot this version with Brain\Cortex::boot(); and use add_action('cortex.routes', function(Routes $routes) {});?

I'm still using

add_action('brain_init', function ($brain) 
{
    $brain->addModule(new Brain\Cortex\BrainModule);
});
add_action('setup_theme', function ()
{
    Brain\Container::boot(new \Pimple\Container);
}, 0);

... and it's working.

tnks

get_post() does not work

I set this route:

$routes->addRoute(new QueryRoute(
    "/corsi/{slug:[a-z0-9\-]+}",
    function (array $matches) {
        return [
            'post_type' => 'product',
            'name'      => $matches['slug'],
        ];
    }
));

But if I call get_post() inside template, I get false, instead of the WP_Post object.

I believe the problem is due to WordPress 6.0

Overriding `template_include` hook

I'd like to override the template_include hook so I can integrate some basic template inheritance. However it doesn't seem possible, because you remove all other filters on the hook.

(Essentially I'm trying to always load a base.php template, then set the actual template as a static class property or something so I can include( InheritTemplate::$actual_template ); within the base template file.)

Is it possible to override that at all? Or is there a better way to accomplish this that I've missed?

AJAX requests handling - how to set up CORS?

Hi,

I'd like to use Cortex to handle AJAX requests, but I have a problem with CORS. I cannot use the allowed_http_origins filter because this filter only affects AJAX requests that are performed in a standard WordPress way.

Is there any way to send origin headers before the request is handler by Cortex?

I tried to call send_origin_headers() within the before callback, but it doesn't work.

add_filter('allowed_http_origin', function ($origin, $origin_arg) {
    $allowedHosts = $this->config->get('ajax:allowed_hosts');
    // $isAllowed = some logic here...
    return $isAllowed;
}, 10, 2);

$routes
    ->addRoute(new ActionRoute(
        self::TRANSACTION_REGISTRATION_URI,
        function () {
            $this->registerTransaction();

            die;
        },
        [
            'method' => 'POST',
            'before' => function () {
                send_origin_headers();
            },
        ]
    ))

How to add body classes depending on a Cortex route - the right way.

I know that I could use do_action('my_custom_action') / did_action('my_custom_action') check as follows:

add_action('cortex.routes', function (RouteCollectionInterface $routes) {
    $routes->addRoute(new QueryRoute(
        '/my/route',
        function (array $matches) {
            do_action('my_custom_action');
            return [
                // params
            ];
        }
    ));
});

add_filter('body_class', function ($classes) {
    if (!did_action('my_custom_action')) {
        return $classes;
    }

    return array_merge($classes, ['my_class']);
});

or I could add some custom query variable and then add custom classes depending on the query variable existence... but none of these methods sound right to me.

Is there a more elegant way?

Issue with wordpress v6

Hi,
Thank you for your great work. I'm using cortex from past year. But recently there is an issue with wordpress v6.
Cortex routes not working, Would you please help?

post__in not working

Hi, I want to have a route with my desired woocommerce products based on "post__in". But seems it's not working and all of the products returns. Here is my code:

 add_action('cortex.routes', function(RouteCollectionInterface $routes) {

        $routes->addRoute(new QueryRoute(
        'store/{slug:[a-z-]+}',
        function(array $matches) {
            $founded_store = $matches['slug'];
            $post_in = KHS()->model()->get_products_ids_by_store_slug($founded_store);

            return [
                'post__in'          => $post_in,
                'post_type'         => 'product',
                'order_by'          => 'post__in',
                'order'             => 'ASC'
            ];
        }
   ));

});

i would appreciate if you would help

PHP Fatal Error·Interface 'Psr\Http\Message\UriInterface' not found

Hi,

I'm having a curious bug here. Cortex and my code works great in my staging environment, but as soon as I pull to production I get this error:

PHP Fatal Error·Interface 'Psr\Http\Message\UriInterface' not found

screen shot 2016-03-09 at 4 30 41 pm

I've been unable to find a solution. Any tips?

I'm using "brain/cortex": "~1.0.0"

Route middleware

Is it possible to register route middleware? I know it's possible to add the 'before' callback, but can these be chained?

I'd like to add an auth check (if user is logged out, redirect to login page) to a big group of routes, but still need to be able to use the 'before' callback for other purposes on some routes.

Thanks!

PHP dependency conflict: "psr/http-message" now requires PHP 7.2

Cortex does not lock the required version of "psr/http-message":

{
  "require": {
    "psr/http-message": "*"
  }
}

This package released v2 requiring PHP 7.2, and it updated the signature of its methods to make use of PHP 7.2 features.

Now, when using Cortex with PHP 7.1, we get an error:

2023-04-08T08:15:22.016874876Z [Sat Apr 08 08:15:22.016525 2023] [php:error] [pid 1179] [client 172.19.0.2:59764] PHP Fatal error:  Declaration of Brain\\Cortex\\Uri\\PsrUri::getScheme() must be compatible with Psr\\Http\\Message\\UriInterface::getScheme(): string in /app/wordpress/wp-content/plugins/graphql-api/vendor/brain/cortex/src/Cortex/Uri/PsrUri.php on line 55

If Cortex were to still require PHP 5.5, I guess the best way to fix the issue is to lock the dependency to version 1.0.1, which is the last version on PHP 5.3.

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

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.

Routes "players" and "players/" are treated as same url

Hi. I'm using "brain/cortex": "*@dev" == "version": "dev-refactoring-fastroute"
Works fine so far, except I've found it treats route "/players/" exactly the same as "/players", meaning my application will have duplicate urls which is bad for SEO and possibly for static caching.

I've found that in your code you are using trim(path, /).
I've also found that unlike your example on frontpage

$routes->addRoute(new QueryRoute(
	    '^post/latest$',

route doesn't support regex, just plain text. Please correct me if I'm wrong, that could solve my issue.

I've tried to edit few pieces of your code, replaced trims with ltrim, with some relative success. I don't like editing /vendor/ anyway, and for you it could be a breaking change.

I've also found that I could manually do it on mod_rewrite level, like

# have to redirect just my custom urls, must not redirect wordpress urls, permalinks do end with /
RewriteEngine on
RewriteCond %{REQUEST_URI} ^/test.*/$ [OR]
RewriteCond %{REQUEST_URI} ^/player/.*/$ [OR]
RewriteCond %{REQUEST_URI} ^/players/$ [OR]
RewriteRule (.*)/ $1 [R,L]

that's my way to go at the moment, but could you please provide a way to do it properly, with code, not with hacks? My common sense tells me it must be easy to just force exact match, why is your framework treats technically different urls like it's the same without a way to distinguish.

Thanks.

P.S.: also I'm never using and not planning to use routes system to query WP items, just building a system with custom code and custom mysql queries, which runs alongside wordpress. Using ActionRoute() and just failed to add RedirectRoute because of issue described above, 'players' and 'players/' are treated as same route.
Only wordpress thing I'm using is it's templating, rendering my output between get_header() get_footer(). Maybe using nikic/fast-route directly is the way to go for me?

Sage 9 Integration

I'm trying to use Cortex with the Sage 9 theme. This seems like another issue with overriding the template_include action. Is there a possible workaround to get this to work with the new template structure?

Defaults and host information in route groups

Hello Giuseppe,

As told in the prior issue report there were other minor issues we've uncovered. Both other issues concern the grouping functionality.

  1. Setting a host in a route group does not appear to have any effect.
  2. Setting defaults for parameters that do not appear in the url do not get applied.

Because there are obvious workarounds we have not taken the time to look into the reason for these issues. It would be nice to have a fix for this, but it's not like we can't do without this functionality.

Cheers,
Wouter van Dam

Preserving variables?

I'm trying to find out if it's possible to preserve some variables for reuse and automation. My goal is to allow a certain type of widget to create a route for each instance, using that widget's settings.

Example:

$widget_instances = get_option( 'widget_mywidgetname', false );
				
foreach ( $widget_instances as $instance ) {
	$title = sanitize_title( $instance['title'] ); // use widget slug as url
	$routes->addRoute( new QueryRoute(
		$title,
		function( array $matches ) {
			$instances = array_values($widget_instances);
			
			$value = $instance['title']; // use widget title as a way to find the query
			$key = array_search( $value, array_column( $instances, 'title' ), true );
			$match = $instances[$key];

			$query = array(
				'post_type' => 'post',
				'tax_query' => array(
					'relation' => 'OR',
					array(
						'taxonomy' => 'category',
						'field' => 'term_id',
						'terms' => $match['widget_categories'],
					),
					array(
						'taxonomy' => 'post_tag',
						'field' => 'name',
						'terms' => explode( ',', $match['widget_terms'] ),
					),
				)
			);

			return $query;
		},
		['template' => 'template.php']
	));
}

This currently doesn't work because the $value is unknown inside the function(array $matches ) { line. Having a bit of trouble thinking of a way to preserve it from the foreach.

I'm also interested in whether that $value url could be passed to the template.php file itself, so that template could be used for all the routes being created, and display the correct title from the widget.

I realize this might be a weird use case, but I'm curious about its feasibility.

Cortex is not booted

The hook brain_loaded is never fired, if I use init I get Domain Exception. It is thrown when a Brain module was not booted if I understand correctly.

I have Brain\Cortex::boot() in my theme's functions.php file. Is it too late to boot it?

ActionRoute leads to warning in class-wp

Hi,

may be I'm doing something wrong in the first place, but here is a finding (Cortex 1.0.0.):

I'm using the ActionRoute and figured out that this will force 'do_parse_request' in class Cortex around line 65 to stop.

In that case $wp->query_vars is null which leads to the warning:

Warning: array_keys() expects parameter 1 to be array, null given in /var/www/ccc/wp/wp-includes/class-wp.php on line 500

So it's actually a problem with wordpress setting query_vars to an empty array after the filter

        if ( ! apply_filters( 'do_parse_request', true, $this, $extra_query_vars ) )
            return;
        $this->query_vars = array();
        $post_type_query_vars = array();

in class-wp.php, which is apparently too late.

I've fixed this by extending Cortex:boot() like:

       self::$booted = add_filter('do_parse_request', function ($do, \WP $wp) use ($request) {
            self::$late = true;
            try {
                $instance = new static();
                $do = $instance->doBoot($wp, $do, $request);
                unset($instance);
                if (!$do){
                    $wp->query_vars = array();
                )
                return $do;
               ......

Warning gone, but not sure if there isn't a better way to do it.

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.