I’m developing WordPress theme for my friend’s company, but this question is all about PHP so writing here, on SO.
I have two sidebars, that’s how we display sidebars in WordPress:
if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('SidebarName') ) :
endif;
So that’s an if statement.
Ok, now, I want to display ONE sidebars IF $layout=”one” TWO sidebars IF $layout==”two” etc.
This code works, but it duplicates sidebars contents I believe endifs are messing with the parent loops or something like that:
if($layout="one") {
if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('Sidebar 1') ) :
endif;
} elseif($layout=="two") {
if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar(' Sidebar 1') ) :
endif;
if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('Sidebar 2') ) :
endif;
} elseif($layout=="three") { (...)
How to fix that issue? When I just delete the main if loop – everything work like expected, so I’m sure I got lost somewhere above.
Sorry, typos, I’m using $layout== instead of =
There’s no such thing as an “
if
loop”. 🙂Since you’re basically only repeating the same condition again and again, you can logically restructure it to this:
This should also take care of the syntax/typo problems that are causing your script to misbehave.
Edit: I just did a test and it looks like this answer is wrong. I was able to mix colon and brace if and while syntax together. However, the manual does state:
So I’m a bit confused about this.
PHP If statements have two types of syntax, one with braces, and one with colons.
and
There are also similar syntaxes for while, for, foreach etc. But you aren’t allowed to mix the braces with the colon syntaxes. So you need to either change your code to
or
You can read more about it at http://php.net/manual/en/control-structures.alternative-syntax.php
Edit: How silly of me I didn’t notice this. Like the other answers say, you have used a single equals sign instead of two to test for equality.
I agree with Michael and also, I’m not sure how your functions are set up but usually I’d see something more similar to
Looks like you mean to use the equality operator
==
where you’re using the assignment operator=
By the way, consider also using the more common
if/else
PHP syntax. Rather than using theelseif
andendif
use this syntax. Brace according to your conventions and preferences.First, this is wrong:
Always use
==
or===
in anif
statement (same forelseif
) because=
actually assigns the value. This is probably part of what’s causing your bug.Better yet, in this particular situation, use the
switch
statementThird, you don’t have to keep copying
!function_exists('dynamic_sidebar')
just put it in once. It should look like this:Even better still, change the whole thing to a number and just do a for loop: