Reputation: 345
I am trying to use a FOR loop to write dynamic CSS. The CSS needs to change based on how many items are in a database table. Here is my attempt, but it is not giving me the output I desire:
<?php
$count_posts = wp_count_posts( 'portfolio' )->publish; // This is for a wordpress site.
$slidecount = ceil( $count_posts / 3 ); // there are 3 database entries in each "slide".
for ($c = 0 ; $c < $slidecount; $c++){
echo '#slide' . ($c + 1) . ':checked ~ #controls label.c-label' . ($c < $slidecount ? (($c + 2) . ', ') : '1'); // This is the part I'm not sure on... How do I properly nest the ($c + 2) expression into a shorthand if/else statement ??
}
echo ' {' . "\n" . 'float: right;' . "\n" . 'display: block; }' . "\n";
?>
Output (when there are 5 items in the database table):
#slide1:checked ~ #controls label.c-label2,
#slide2:checked ~ #controls label.c-label3,
#slide3:checked ~ #controls label.c-label4,
#slide4:checked ~ #controls label.c-label5,
#slide5:checked ~ #controls label.c-label6 {
float: right;
display: block;
}
Desired output:
#slide1:checked ~ #controls label.c-label2,
#slide2:checked ~ #controls label.c-label3,
#slide3:checked ~ #controls label.c-label4,
#slide4:checked ~ #controls label.c-label5,
#slide5:checked ~ #controls label.c-label1 {
float: right;
display: block;
}
I want the last execution of the FOR loop to append a '1' to the end of 'label', so that the CSS selector points back to the first element "c-label1". This is being used to build a pure CSS slider that changes the slides using radio buttons and needs to loop the slides back to the beginning once it gets to the end. I need the code to automatically update whenever there is a new database entry saved.
Can anyone help me clean up the code so it works?
Thank you SO much in advance.
Upvotes: 2
Views: 114
Reputation: 1143
In your for loop condition you have
$c < $slidecount
It means that the same condition in your loop body is also met, so your code to generate c-label1 will never be executed.
Try changing
$c < $slidecount
to
($c < ($slidecount-1))
Upvotes: 2
Reputation: 23490
This is happening because you are using $c < $slidecount
in your statement but your $c
value starts from 0 so it will never happen to match your slidecount
and won't be false.
You should also change your round bracket ()
A quick solution could be to add 1 to your $c
variable. This should work
(($c+1) < $slidecount ? ($c + 2) . ', ' : '1');
Upvotes: 1
Reputation: 24703
It is how you are using (
and )
. try this:
echo '#slide' . ($c + 1) . ':checked ~ #controls label.c-label' . ($c < $slidecount ? $c + 2 . ', ': '1');
Upvotes: 0