Move comments section before the footer

I recently run into a case where a client wanted to have the comments section appear below the main body content but also after the collapsed sidebar on smaller mobile screens. By default, the sidebars are the ones that appear last when they are collapsed to mobile with the comments section above them. In addition, there is no easy way of rearranging them to achieve the required result. But after GeneratePress v. 3.0, the comments section is actually hooked into the main template content.

We can, thus, unhook it from its original location and hook it whenever we want! By using the generate_before_footer hook, we can move the comments area just before the footer.

add_action( 'wp', function() {
    remove_action( 'generate_after_do_template_part', 'generate_do_comments_template', 15 );
} );

add_action( 'generate_before_footer', function() {
    if ( is_page() || is_single() ) {
        if ( comments_open() || '0' != get_comments_number() ) :
            /**
             * generate_before_comments_container hook.
             *
             * @since 2.1
             */
            do_action( 'generate_before_comments_container' );
            ?>

            <div class="comments-area">
                <?php comments_template(); ?>
            </div>

        <?php
        endif;
    }
} );

Lastly, a little bit of CSS to tidy things up like constraining the comments section’s width to our main site container and also center it.

.comments-area {
	max-width: 1300px;
	margin: 0 auto;
	padding: 0 20px;
}

@media (min-width: 769px) {
	.comments-area {
		padding: 0 40px;
	}
}

In my case, my site container is 1300px wide and my main container has 40px left and right padding and 20px left and right padding on mobile.