Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

WordPress

Evan Fraser
Evan Fraser
6,789 Points

Sidebar wont go away when custom metabox is unchecked (see code)

I am adding the functionality to my posts and pages post types to show or hide the sidebar when a select box is checked in the post. When checked, a with-sidebar class will be put in the body tag and the post displays fine, but when unchecked, the sidebar appears at the bottom of the document even though I am not calling it in the page file, i dont want the sidebar to appear at all when the metabox field is unchecked

(im new to this so please explain in simple terms with what i should do, i cant write php yet, but i can kind of see what its saying) Thanks!

Here is my meta-boxes.php file

<?php
/**
 * mytheme metaboxes
 *
 * @package WordPress
 * @subpackage mytheme
 */

// Add a page options checkbox Meta Box
function page_options_checkbox_init() {
    $post_types = array ( 'post', 'page' ); // Create an array to display metabox in both posts and pages
    foreach( $post_types as $post_type ) {
        add_meta_box(
            "page_options_checkbox", // id
            "Page Display Options", // title
            "page_options_checkbox", // call back
            $post_type,
            "side", // context
            "low" // priority
        );
    }
}
add_action("admin_init", "page_options_checkbox_init");

// Add inputs to pages
function page_options_checkbox($post) { 
    $sidebar_value = get_post_meta($post->ID, 'sidebar', true);
    wp_nonce_field('global_meta_box', 'global_meta_box_nonce'); ?>
    <p><label>Show Sidebar&nbsp;&nbsp;<input type="checkbox" name="sidebar" value="yes" <?php checked( $sidebar_value, 'yes' ); ?> /></label></p> <?php
}

// Save Meta Details
function save_page_options($post_id){ 
    if ( !isset( $_POST['global_meta_box_nonce'] ) )     { return; } // Check if our nonce is set.
    if ( !wp_verify_nonce( $_POST['global_meta_box_nonce'], 'global_meta_box' ) ) { return; } // Verify that the nonce is valid.
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) { return; } // If this is an autosave, our form has not been submitted, so we don't want to do anything.
    if ( !current_user_can( 'edit_post', $post_id ) )    { return;  } // Check the user's permissions.
    $page_sidebar = ( isset( $_POST['sidebar'] ) ? sanitize_html_class( $_POST['sidebar'] ) : '' ); // Sanitize user input.
    update_post_meta( $post_id, 'sidebar', $page_sidebar ); // Update the meta field in the database.
}
add_action('save_post', 'save_page_options');

// check for 'sidebar' meta key on pages and add a body class if meta value equals 'yes'
function hawp_add_custom_body_class( $classes ) {
    global $post;
    $show_sidebar = get_post_meta( get_the_ID(), 'sidebar', true );
    if ( is_page() && ( 'yes' == $show_sidebar ) ) {
        $classes[] = 'with-sidebar';
    } 
    return $classes; // return the $classes array
}
add_filter('body_class','hawp_add_custom_body_class');

Here is the page.php file

<?php
/**
 * The template for displaying all pages
 *
 * This is the template that displays all pages by default.
 *
 * @package WordPress
 * @subpackage mytheme
 */

get_header(); ?>

<div id="content">
    <div class="contain">

        <?php 
            if ( have_posts()) :

                // Start of the loop
                while ( have_posts() ) : the_post();

                    get_template_part( 'template-parts/page/content', 'page' );

                    // If comments are open or we have at least one comment, load up the comment template.
                    if ( comments_open() || get_comments_number() ) :
                        comments_template();
                    endif;

                // End of the loop
                endwhile; 

            endif; 
        ?>

        <?php
            // If sidebar is checked in display page options
            $show_sidebar = get_post_meta( get_the_ID(), 'sidebar', true ); 
            if ($show_sidebar != "no") { get_sidebar(); }
        ?>

    </div><!-- .content-section -->
</div><!-- #content -->

<?php get_footer();

If you know of a simpler way to write this, feel free to let me know. Appreciate the help!

1 Answer

Liam Maclachlan
Liam Maclachlan
22,805 Points

Hi Evan,

I'd recommend changing the line

if ($show_sidebar != "no") { get_sidebar(); }

to be

if ($show_sidebar === "yes") { get_sidebar(); }

I think the problem you are having is that when the box is unchecked the value of $show_sidebar isn't "no", or there no value stored at all (so it still doesn't equal "no"). Give this a try and let me know if it works.

Cheers :)