Roots Discourse

Call helper function from filters.php

Hello,

im using the latest sage 9 and having an issue calling a helper function from filters.php

I have a test function in helpers.php

function yarr() { return 'yarr'; }

I can see that I call this within a blade template as:
{{ App\yarr() }}

However, how do I call it from a hook in filters.php:

`function action_woocommerce_after_checkout_form( $wccm_after_checkout ) {

	// I can add custom text to the basket
	echo 'Test text';
	// but I cannot call the helper function ???
	echo yarr();
	return $wccm_after_checkout;

};`

Many thanks,
Darren

Hey @daz,

It sounds like you’re doing it right. In a stock Sage theme, if your function is defined in helpers.php, it should work in filters.php. See the display_sidebar() function as an example.

Here’s another test that works:

helpers.php

function greet_daz()
{
    return "Hello, Daz!";
}

filters.php

add_filter('the_content', function ($content) {
    return $content . greet_daz();
});

Result

image

perfect! - thanks soo much!!

Your answer helped lots as I forced me to see what I was actually doing wrong.

I was trying to separate filters.php into different files to keep the code more organised. I had created :slight_smile:filters-checkout.php
filters-basket.php
filters-posts.php
etc

I tried including them in filters.php with
include('filters-checkout.php');

but this didn’t work… I also tried the correct way of added new filter files in functions.php

but no function could be called from any new filter… file.

The issue in case anyone else has this, is to add the namespace to the top of your custom filter file:
namespace App;

Thanks so much for your help @mmirus

Yep, easy to forget the namespace declaration if you’re not in the habit. I personally have a snippet in VS Code that I use when I start all my PHP files that makes sure I have that in there as well as declare(strict_types=1);.

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