I am developing a theme the pages of which (as well as posts) are so different from the home page that I want different widgets on their sidebars.
Is there a way to do it?

I’m calling the sidebar on single.php this way, exactly as it’s on index.php:

<?php get_sidebar(); ?>

The sidebar.php is this way:

<?php
/**
 * The Sidebar containing the primary and secondary widget areas.
 ?>

    <aside>
        <ul>

<?php
    /* When we call the dynamic_sidebar() function, it'll spit out
     * the widgets for that widget area. If it instead returns false,
     * then the sidebar simply doesn't exist, so we'll hard-code in
     * some default sidebar stuff just in case.
 */
if ( ! dynamic_sidebar( 'primary-widget-area' ) ) : ?>


    <?php endif; // end primary widget area ?>
    </ul>

<?php
    // A second sidebar for widgets, just because.
    if ( is_active_sidebar( 'secondary-widget-area' ) ) : ?>

        <ul>
                <?php dynamic_sidebar( 'secondary-widget-area' ); ?>
        </ul>

<?php endif; ?>

    </aside>

1 Answer
1

Use Conditional Tags to show content only if a certain condition is met.

In your case, you’re probably looking to use is_front_page().

<aside>
    <ul>

    <?php
        if ( function_exists( 'dynamic_sidebar' ) ) {
             if ( is_front_page() ) {
                 if ( ! dynamic_sidebar( 'frontpage-widget-area' ) ) {
                     echo '<li>No sidebars for the frontpage.</li>'; // some default output
                 }
             } else {
                 if ( ! dynamic_sidebar( 'primary-widget-area' ) ) {
                     echo '<li>No sidebars for posts/pages.</li>'; // some default output
                 }
             }
        } else {
            echo '<li>Sidebars disabled.</li>'; // some default output
        }
    ?>

    </ul>
</aside>

That’s assuming, the two widget areas have been properly registered via register_sidebar() beforehand.

Leave a Reply

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