__construct() method now runs before the $post object is loaded
pridyok opened this issue · 10 comments
After updating to 2.0.1 I found a lot of my code broke as it was based assigning data to a variable via get_field('content')
in the __construct()
method. It seems as though get_field()
no longer works here, as the global $post
variable is not accessible at all. Was this change intentional?
It wasn't, I'll take a look at this tomorrow.
Awesome, thank you.
@pridyok could you give me a use case of code that's now broken? I think it's because $post is only being passed in App, and not Controllers that live up the hierarchy. But just want to confirm with some of your code.
@darrenjacoby I'm also experiencing this. Everything worked fine on 9.0.0-beta.4 but now updating to 2.0.1 I am unable to do anything with the $post
object in class constructors (which prevents the possibility of using get_field
).
If I put the following into my App.php
constructor, it returns nothing:
<?php
namespace App\Controllers;
use Sober\Controller\Controller;
class App extends Controller
{
public function __construct()
{
error_log(print_r($post,1));
}
}
Output:
[12-May-2018 20:00:41 UTC]
If I move that code to a function on the class, everything works fine:
public function post()
{
error_log(print_r($post,1));
}
Output:
[12-May-2018 20:05:10 UTC] WP_Post Object
(
[ID] => 9
[post_author] => 1
...
@darrenjacoby I have a trait that I load into App.php that pulls the values from an ACF flexible content field:
<?php
namespace App\Controllers\Partials;
trait Components
{
public static $components;
public function __construct() {
self::$components = get_field('content');
}
...
<?php
namespace App\Controllers;
use Sober\Controller\Controller;
class App extends Controller
{
use Partials\Components;
...
Initially I thought this may be an issue with implementing this in the trait, but when I tested moving the code to App.php it had the same results.
Thanks guys, going to check this out now. I'll get back to you.
OK, I see what's happening here. In the past, I created the class within the filter, so it could pull in $post. I cleaned up the Loader in 2.0.0 and as a result I create the Class outside the filter.
If I just init the class in the filter, it works as should. I'll include this in the next release. If you want a quick fix now that won't break on the upgrade, add this to vendor/soberwp/controller/controller.php
from line 38
// Pass data to filter
add_filter($location, function ($data) use ($container, $class) {
// Recreate the class so that $post is included
$controller = $container->make($class);
$controller->__setParams();
// Return the data
return $controller
->__setControllerData()
->__setIncomingData($data)
->__getData();
});
Let me know if that solves it for you.
Thanks @darrenjacoby, I'll take a look and get back to you 👍
Works great @darrenjacoby thanks :)
2.0.2 out now