Forums

Showing a different sidebar for posts in a category (3 posts)

  1. Bandbreed
    Member
    Posted 1 year ago #

    Some tricky PHP required and I cannot figure it out myself, what I need is basically a combo of these two posts:

    WordPress Codex: in_category

    Different sidebar for each category?

    What I have now is a generated sidebar for each category which automatically shows custom widgets on each category view.

    What I need is that same sidebar to show up on each post within that category and I cannot get it to work. Right now I load the dynamic sidebar like this:
    <?php dynamic_sidebar( 'Sidebar '.$category_name ); ?>
    but that does not show anything when you view a single post.

    In the function.php I generate the dunamic sidebars by running a loop through all categories. In wordpress users can fill each sidebar with widgets just like they want.

    How can I get that right sidebar to show up for posts in the right category? I tried using the in_category function but that does nothing, I think because it is loaded from the sidebar.php and that is not in any loop or something... Need help, thanks.

  2. t-p
    Member
    Posted 1 year ago #

  3. Bandbreed
    Member
    Posted 1 year ago #

    Thanks T-P but the solution in that thread (which I found before coincidentally) shows a solution to a problem I already fixed. Only instead of creating separate php files for each category, I generate a dynamic sidebar from the functions.php file for each category in WordPress, saves some work and you can never make mistakes or forget one.

    But.

    What that does not do is show the sidebar for single posts which belong to the same category. For example, I have a category Fruit with two posts, apples and pears. When you view the category fruit, you see the excerpt of apples and pears and the sidebar meant for the fruit category. But when you look at apples or pears only (single view) it does not load the sidebar connected to the category fruit.

    The code in both category.php and single.php are the same:

    <?php get_sidebar(); ?>

    and in the sidebar.php I load the following code, which loads a dynamic sidebar with name "Sidebar Category" where category is the nice name of the category you are viewing.

    <?php dynamic_sidebar( 'Sidebar '.$category_name ); ?>

    But in single.php this does nothing and I tried a lot of different ways to look for the correct (parent) category but no such luck. I thought it might be in the function "in_category" but I cannot get that to work besides breaking the sidebars for categories as well.

    I hope I made the problem a bit clearer.

Topic Closed

This topic has been closed to new replies.

About this Topic