Getting ACF value within a controller

Heya!

So, I recently forced myself to get my head around Sage 9 on a new project, after hanging onto Sage 8 for ages, and overall now that I’m off to the races with it, I’m loving the improved data/template separation. In particular, I’m loving the Controllers implementation.

One question that I’ve got though: I’m making heavy use of the automated ACF variable passing via the controller to the view (this is really great) — but I’m not clear on how to access those same variables within the controller, without resorting to additional/redundant get_field() calls.

I kinda thought that after including protected $acf = true; in the controller, I’d be able to access ACF vars using the $myvar syntax, as in the view, but this doesn’t seem to be the case? Since the ACF vars are already being loaded using the protected $acf = true; directive, I’d like to be able to access them without having to make redundant get_field() function calls, inside the controller, if possible.

Thoughts? Am I missing something here?

Thanks!

I don’t think you can do this. Based on my understanding of how Controller works, the ACF fields aren’t “loaded” when you’re “in” the controller; They get loaded when the data generated and compiles for the Blade views.

I’m not sure why you’re so opposed to using get_field(). IIRC there’s no performance penalty: AFAIK when you query any meta field on a post (which is all ACF fields are) it gets all of them, and caches them, so it’s not like every get_field() is another DB call. If you want to get something containing all the fields instead of doing get_field() one by one, you could always call get_fields() (which is actually what the ACF module for Controller is doing).

2 Likes

Thanks for the quick response!

I’m not terribly opposed to using get_field() inside the controller if there’s no performance hit — if that’s the case, then I’ll probably just do that! :slight_smile:

Thanks for the insight!!

This topic was automatically closed after 42 days. New replies are no longer allowed.