Normal controller methods are set up before your template does its thing. As noted in the Controller documentation, to pass a variable you’ll need to use a static method.
Also, just curiously, if pests
is a customs post type, there a reason you’re using a sanitized title
and not its existing slug
when creating your anchor links and id
s?
Finally, if you’re populating an list of anchor links and a page of content at the same time, you might benefit from stacks. It would mean an overhaul of your templates, but ultimately more maintainable with fewer moving parts. Not necessary but super cool!