How To Add A Filter Function In Sage 9

By August 8, 2017Blog, Sage, Wordpress
WordPress Tutorials by Allure Web Solutions

In this post I’ll show how to add a filter function to a Sage 9 project. A filter function is a good method for selectively hiding or showing certain functionality. The filter function I’ll be showing is for the sidebar, which for some reason doesn’t come shipped with a base Sage 9 project. My example also includes how to target a custom page template.

The below code goes into your app/filters.php file.

/**
 * Display sidebar
 */
add_filter('sage/display_sidebar', function ($display) {
    static $display;

    isset($display) || $display = in_array(true, [
        // The sidebar will be displayed if any of the following return true
        is_home(),
        is_single(),
        is_search(),
        is_archive()
    ]);

    // example if you want to target a particular custom page template
    if (basename(get_page_template()) == "template-full-width.blade.php")
        $display = false;

    return $display;
});

You may also want to add a class to the body for pages that have an active sidebar. The code below comes shipped with Sage 9 and adds a sidebar-primary class to the body.

/** Add class if sidebar is active */
if (display_sidebar()) {
    $classes[] = 'sidebar-primary';
}

To actually use this, you would need to call the filter function. Sage 9 does it by default for the sidebar in resources/views/layout/app.blade.php.

@if (App\display_sidebar())
    <main class="main col-md-8">
        @yield('content')
    </main>
    <aside class="sidebar col-md-4">
        @include('partials.sidebar')
    </aside>
@endif

I’ve used filter functions in multiple scenarios. In one case, I had a secondary navigation for sub-pages that I didn’t want to show on a full-width template. In another case, I had post filtering that was supposed appear on the post page, but not on the home page.

Mike Doubintchik

Author Mike Doubintchik

More posts by Mike Doubintchik

Leave a Reply