Creating multiple WordPress category divs

I have a WordPress site which uses images replacing category text. It is set up to have a post div (padding: 20% 0; for consistent responsive height ) Then has a div positioned absolute, vert/horiz centred overtop this div.

html

Read More
<div class="indx-img" style="background-image:url('...');">

        <?php 
        $testStyle = "";

        if(has_category( 'update' ) || has_category( 'uncategorized' )) {
            $testStyle = "style="background-image:url('".get_bloginfo('template_directory')."/img/logo.png')"";
        } elseif(has_category( 'event' )) {
            $testStyle = "style="background-image:url('".get_bloginfo('template_directory')."/img/logo.png')"";
        }
        ?>

            <div class="test" <?php echo $testStyle; ?>></div>

</div>

CSS

.indx-img {
  position: relative;
  padding: 20% 0;
}

.test {
   position: absolute;
   left: 50%;
   margin-left: -5em;
   transform: translateY(-50%);
   -webkit-transform: translateY(-50%);
   -ms-transform: translateY(-50%);
  height: 10em;
  width: 10em;
}

This put’s a background image for test. The problem with this is if a post has more than one category on it, only one will show.

Ideally I want a div created in ‘test’ for each category applied to the post with the category-image, aligned next to each other.

Related posts

1 comment

  1. By your code, I guess that your HTML div code is running for single post. and as you are checking for single category with has_category, it will give you on category only.

    For getting all category of any post, you would required wp_get_post_categories function.

    $post_categories = wp_get_post_categories( $post_id );
    $cats = array();
    
    foreach($post_categories as $c){
        $cat = get_category( $c );
        $cats[] = array( 'name' => $cat->name, 'slug' => $cat->slug );
    }
    

    In this way, you can get category list and can put apply style code accordingly. see https://codex.wordpress.org/Function_Reference/wp_get_post_categories more details of wp_get_post_categories usage.

Comments are closed.