I’m trying to output custom fields using the best practices from the Sage book (wonderful read, worthy buy!). However I’m just not getting it! I have tried both the filter method and the controller method, to no avail.
Thanks a bunch! If I don’t get it working I’ll disable soberwp/controller.
I tried to implement Controller like this:
<?php // @app/controllers/front-page.php
namespace App;
use Sober\Controller\Controller;
class FrontPage extends Controller
{
public function shortDescription()
{
return get_field('short_description');
}
}
And in front-page.blade.php:
{!! $short_description !!}
I’m only using controller to get title and siteName, from the standard setup after installing sage with Composer, so I might just as well remove it. Would still like to get it to work though
If you’re using a newer version of Controller (i.e. 2.0.0) then your controllers need to conform to PSR-4. In this case, that means that front-page.php needs to be FrontPage.php. Additionally, the namespace for Controllers has changed w/ 2.0.0, so you need to change the namespace to App\Controllers.
I updated to version 2.0.0 of Controller, but ran into further issues!
Fatal error: Uncaught ReflectionException: Class App\Controllers\App does not exist in /Users/nadal/Web/lakegarden/web/app/themes/lakegarden/vendor/soberwp/controller/src/Loader.php:119
Perhaps I should just remove Controller and work with filters instead. HOwever when I remove Controller I run into further issues… hmmm
OK, I solved the issue with upgrading to 2.0.0 from help from other forum posts! I still cannot access ACF data from neither controllers nor filters.
This is my FrontPage.php controller:
<?php // @app/controllers/FrontPage.php
namespace App\Controllers;
use Sober\Controller\Controller;
class FrontPage extends Controller
{
public function shortDescription()
{
return get_field('short_description');
}
}
And this is how I’m calling it:
{!! $short_description !!}
If I try changing the return statement to just return a string, it works perfectly, so there is some issue with calling the custom field. Any idea?
That is correct, it is in a loop of other posts. So what’s the benefits of using it in a controller rather than just calling get_field in the template?
I honestly go back and forth. If I don’t have any other messy logic (like I don’t need to deal with whether short_description is blank) then I’ll sometimes call get_field() in the blade files.
I’ll see if I can get it working properly - I’m planning to use the get_field in another controller which loops over custom queries, so I’ll have to try getting it working in the controller.