Working on my first sage project and so far all is great.
I had a function that gets called from a number of templates and I wanted to include it in its own name space for the project, but am having issues with this. I know that the file is working as I can call a more simple function in that place no problem. The function is below and somehow the lines starting with return fail the function.
Does it not know what WP_Term $term is in that context and if so, how can I fix this? Would be great not to repeat this function in different files, as it just does the same everywhere.
Thank you with any help on this!
function get_rug_terms_slug($term) {
$terms = get_the_terms( get_the_ID(), $term);
if( !empty($terms) ) {
return implode(", ", array_map(function(WP_Term $term){
return $term->slug;
}, $terms));
}
}
It’s helpful if you give the actual error you’re receiving.
Hi @kalenjohnson, thank you for having a look. Sorry about that, here is the error I am getting.
Catchable fatal error: Argument 1 passed to Roots\Sage\Samsextras{closure}() must be an instance of Roots\Sage\Samsextras\WP_Term, instance of WP_Term given in /Users/brian/Documents/Sams International/6_WebFiles/wp-content/themes/sams/lib/sams_extras.php on line 9
Here is how I was calling the function:
$the_terms = Samsextras\get_rug_terms_slug(‘collection’);
And your error shows what’s happening. Your function is declared in a namespace, so you have to make sure you are specifying any classes that are used in the correct namespace. Roots\Sage\Samsextras\WP_Term
does not exist.
So in the file where get_rug_terms_slug
is declared, you either add underneath the namespace
declaration use WP_Term;
in order to tell PHP where that class is located (global namespace), or else when you use it, prefix it with a forward slash, return implode(", ", array_map(function(\WP_Term $term){
3 Likes
Yes, perfect! Thank you, that worked great! I added the use WP_Term; to the file.
Thank you very much!