Okay! I did some digging into this, and it looks like what’s happening is that the version (currently: 9.0.0-beta.4
) of soberwp/controller
bundled with Sage wipes out anything you’ve put into $data
through filters. If you’re not going to use Controller, then there’s an easy fix! Just remove Controller by deleting it from your composer.json
, and running composer update
. I’ve tested that process locally, and it works like a charm.
If you’re interested in a more in-depth examination of the problem, and how I tracked it down, read on…
By sticking a var_dump()
(so elegant) in Sage’s template processing loop, I can see what it’s thinking about:
// app/filters.php
/**
* Render page using Blade
*/
add_filter('template_include', function ($template) {
$data = collect(get_body_class())->reduce(function ($data, $class) use ($template) {
var_dump($data); // Show me that hot, hot $data!
return apply_filters("sage/template/{$class}/data", $data, $template);
}, []);
if ($template) {
echo template($template, $data);
return get_stylesheet_directory().'/index.php';
}
return $template;
}, PHP_INT_MAX);
// Here's what I'm trying to add:
add_filter('sage/template/blog/data', function (array $data, $template) {
$data['augustus'] = 'ceasar';
return $data;
}, 10, 2);
On the front end, what I see is the following:
array(0) { }
array(0) { }
array(1) { ["augustus"]=> string(6) "ceasar" }
array(1) { ["augustus"]=> string(6) "ceasar" }
array(1) { ["augustus"]=> string(6) "ceasar" }
array(1) { ["augustus"]=> string(6) "ceasar" }
array(1) { ["site_name"]=> string(7) "testing" } // UH OH
array(1) { ["site_name"]=> string(7) "testing" }
array(1) { ["site_name"]=> string(7) "testing" }
So where’s that string coming from? From the App controller:
// app/controllers/app.php
class App extends Controller
{
public function siteName()
{
return get_bloginfo('name');
}
}
So why is this happening? This line right here, in the code for Controller:
// vendor/soberwp/controller/controller.php
add_filter('sage/template/' . $template . '-data/data', function ($data) use ($loader, $class) {
$controller = new $class();
$controller->__setup();
return array_merge(
$loader->getAppData(),
$loader->getPostData(),
$controller->__setTreeData($data),
$controller->__getData()
// This should be merging $data as well!
);
});
The point of all this isn’t to call out @withjacoby, who is doing an excellent job (and has already fixed this issue in more up-to-date versions of Controller)—the point is to illustrate how you might go about tracking down a problem like this.
If you want to use both Controller and pass data with filters, you should be able to just manually apply this pull request: https://github.com/roots/sage/pull/2025