This question already has an answer here:
I have a wordpress site where my index page will display the post title, thumbnail, and list all available post categories. Each instance of a post will also display all available post categories. For each category the post has, the category name should be highlighted with a light blue background color. Currently the background color feature is working for only the first post and not the other three.
My code below is intended to push each of the post's categories into an array and search the array for the given category (the code below searches for just one of the categories for brevity's sake here). If the category is found, a jQuery script should execute highlighting the category name but as I say above, it's only functioning for the first post.
Can anyone see what I'm doing wrong? Thanks in advance.
<section class="blog-index">
<?php
$args = array('showposts' => 3);
$recent = new WP_Query( $args );
if( $recent->have_posts() ):
echo '<div class="blog-index-list">';
while ( $recent->have_posts()) :
$recent->the_post();
$categories = get_the_category();
$cats = array();
foreach($categories as $category) {
$cats[] = $category->name;
}
if(in_array("Academia", $cats)) {
echo "<script type='text/javascript'>
jQuery('#A').addClass('active');
jQuery('#A').css({'background-color': #009edb', 'color': '#ffffff'});
</script>";
}
echo '<article>
<h2><hr class="orange-line above-left"> <a href="'.get_the_permalink().'">
<span class="dark-blue">' .get_field('dark_blue_hero'). '</span><br/>
<span class="light-blue">' .get_field('light_blue_hero') . '</span></a>
</h2>
<ul class="all-categories">
<li id="G">G</li>
<li id="A">A</li>
<li id="I">I</li>
<li id="N">N</li>
</ul>
<img src="'.get_the_post_thumbnail().'' .
'<div class="blog-index-button et_pb_button_module_wrapper et_pb_module et_pb_button_alignment_center">
<a class="et_pb_button et_pb_button_3 et_pb_module et_pb_bg_layout_light" href="' . get_the_permalink() . '">READ POST</a>
</div>
</article>';
endwhile;
echo '</div>';
endif;
wp_reset_query();
?>
</div>
IDs should be unique (as Barmar said) but it is still possible to have multiple elements with the same ID. And it is possible to select them with jQuery. That is why I'll also explain how to do it with classes.
When you use the jQuery ID selector (jQuery("#id")
) it selects the first element with the given ID id
.
To select all elements with ID id
you can select them by their attribute(s):
jQuery("li[id=id]")
Since IDs should be unique it is better to use classes. Using the jQuery class selector jQuery(".class")
you can select all the elements with the class class
. You should change your li elements to have classes instead of IDs and select those classes with jQuery.