Search code examples
phpwordpressforeachwoocommercecategories

PHP function with for each loop inside - what to return?


I have navigation with product categories at top of website.

Want to repeat this navigation in footer of website.

Instead of writing $args, defining variables and such once again I decided to make a function for this.

It looks like this:

enter image description here

However as every function should have a return I'm confused how should return of this function look like?

When I try to return <li> instead of echoing it - I get nothing, empty area, but with echo - function works.


Solution

  • Instead of echo you can write $return_data .= ... to concatenate a string which was initially declared as an empty string before the loop began.

    Here is a sample for such cases:

    function show_prod_cats($all_categories) {
        $return_data = '';
        foreach ($all_categories as $cat) {
            //echo '<li>....</li>';
            $return_data .= '<li>....</li>';
        }
        return $return_data;
    }