Remove the Sidebar on certain pages in Wp-Rig

Theme developers often make the design decision to remove the sidebar in certain files. I recently needed to remove the sidebar for all files that used the single.php template. Easy I thought! I dropped the file from the optional folder into the main folder :

optional/single.php --MOVE--> /single.php

the file single.php has a get_sidebar() function that needs to be removed

<?php
/**
 * The template for displaying all single posts.
 *
 * @see https://developer.wordpress.org/themes/basics/template-hierarchy/#single-post
 */

namespace WP_Rig\WP_Rig;

get_header();

wp_rig()->print_styles('wp-rig-content');

?>
	<main id="primary" class="site-main">
		<?php

        while (have_posts()) {
            the_post();

            get_template_part('template-parts/content/entry', get_post_type());
        }
        ?>
	</main><!-- #primary -->
<?php
// get_sidebar() remove sidebar from single.php posts.
get_footer();

But, unexpectedly this actually only gets us halfway – we have the sidebar gone, but we still have it taking up space, on closer inspection, a class is added “.has-sidebar” so let’s work at removing that. Load up ./inc/Sidebars/Component.php

 /**
     * Adds custom classes to indicate whether a sidebar is present to the array of body classes.
     *
     * @param array $classes classes for the body element
     *
     * @return array filtered body classes
     */
    public function filter_body_classes(array $classes): array
    {
        if ($this->is_primary_sidebar_active()) {
            global $template;

            if (!in_array(basename($template), ['front-page.php', 'single.php', '404.php', '500.php', 'offline.php'])) {
                $classes[] = 'has-sidebar';
            }
        }

        return $classes;
    }

find the above code, where you will see an array of pages that don’t have that sidebar class added, just add single.php as I have above. (or whatever template file you need to remove the sidebar).

All done!

Leave a Reply

Your email address will not be published. Required fields are marked *