WordPress.org

Ready to get started?Download WordPress

Forums

About dynamic sidebar and widgets (5 posts)

  1. tlo
    Member
    Posted 4 years ago #

    I am new to wordpress but I understand php. Can someone explain how the following code works to display widgets?

    <?php if ( !function_exists('dynamic_sidebar')
    || !dynamic_sidebar() ) : ?>
    php endif; ?>

    If (!True) it appears not to do any code. And if I do not include this in my sidebar.php, my widgets do not appear.

  2. vtxyzzy
    Member
    Posted 4 years ago #

    It works because of the 'short-circuit' feature of PHP if statements. An 'or' condition test stops on the first true.

    if (TRUE || any-test) is always true, so it stops testing and any-test is never evaluated.

    if (FALSE || any-test) could be true if any-test is true, so any-test must be evaluated.

    So if the dynamic_sidebar function does not exist, the if-test stops.

    If the first condition is false, the if-test continues because one of the following conditions may be true. In this case the result of the second condition is immaterial because the function dynamic_sidebar() is executed.

    Hope that clears it up.

  3. tlo
    Member
    Posted 4 years ago #

    Thanks so much for your reply. I was confused by the fact that there was no code to be executed within the if statement.

    if (true) {
    no code here
    }

    from your explanation, I see that the function dynamic_sidebar() is executed while the if statement is evaluated, if the function exists. If I understand your response correctly, the following snippet would have the same result:

    <?php if (function_exists('dynamic_sidebar')) {dynamic_sidebar();} ?>

  4. vtxyzzy
    Member
    Posted 4 years ago #

    Exactly! You will also sometimes see this:

    <?php if (function_exists('dynamic_sidebar') && dynamic_sidebar()) ...

  5. LiebeTitian
    Member
    Posted 3 years ago #

    Sorry to bother you both, as I see this was closed a couple of months ago, but are we saying that if the 'dynamic_sidebar()' is even queried, using the 'if' statement then the WordPress will call the dynamic sidebar into existence, in the exact place that the function was queried?

    for example:

    lets say that "if(!dynamic_sidebar()):..." was proved to be false, meaning that the dynamic sidebar was actually active, then WordPress would automatically spit out the dynamic sidebar into the place where this conditional if statement was placed?

Topic Closed

This topic has been closed to new replies.

About this Topic