Passing variables to function in Controller

I’m trying to create a function that returns a slug from a title that comes from an array of data id the way of

@foreach($pests as $p)
    <a href="/services/pests-we-control/#{{$p['name-desc']['name']}}" class="text-center pests-carousel-item">
  @endforeach

the problem i’m facing is the name came with spaces in between so i need to make use of sanitize_title in order to convert the spaces in dashes. tried several things, nothing seemed to work, when i tried to pass the data to the controller, im getting

[25-Mar-2018 14:19:08 UTC] PHP Fatal error:  Uncaught ArgumentCountError: Too few arguments to function App\FrontPage::getUrl(), 0 passed in ..../vendor/soberwp/controller/src/Controller.php on line 105 and exactly 1 expected in ..../app/controllers/front-page.php:23


<?php

    namespace App;
    use Sober\Controller\Controller;

    class FrontPage extends Controller
    {
        public function getUrl($title){   <=== is not being passed to the controller
            return sanitize_title('$title');
        }
    }

what i’m doing wrong?

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 ids?

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!

1 Like

pests are not a custom post type, are just childrens of an ACF repeater variable, i’ll take a look into the static methods and stacks. thanks for your help!

thanks @MWDelaney, the static function did the trick. the stacks thingy was too confusing, and i think it was meant for other type of things.