1

I need to add a different custom class to each div inside my wordpress loop. I've read about post_class() function and filter, but I'm not sure if it's a good approach to do this. For now I have this code, and I'm using the get_post_meta() to get the custom field I set with the class I want to display, but it will work only for the second post displayed. Is there a fix or I need to use the post_class() instead?

<?php $scrollable = new WP_Query( ['post_type' => 'home-slider', 'posts_per_page' => 3] ); ?>
<?php if( $scrollable->have_posts() ): while( $scrollable->have_posts() ): $scrollable->the_post(); ?>
<?php $class = get_post_meta($post->ID,'class',true); ?>
      <div class="col-sm-12 col-md-12 col-lg-12 img-<?php echo $class; ?>"> <!-- For each div of the loop I need to assign the img-top ecc... custom class -->
        <div class="row">
          <div class="col-sm-12 col-md-12 col-lg-12 img-text">
            <h1 class="">Hello</h1>
            <p class="lead">Nice to meet you.</p>
          </div>
        </div>
        <img class="img-fluid bg-img" src="<?php the_post_thumbnail_url(); ?>">
      </div>
<?php endwhile; ?>
<?php endif; wp_reset_postdata(); ?>
  • Try to use get_the_ID() instead of $post->ID in the get_post_meta function within a loop. – Pradipta Sarkar Nov 16 at 18:13
  • @PradiptaSarkar already tried, the result is the same. – sialfa Nov 17 at 10:00
-1

In that case try to create custom sql query like this.

global $wpdb;
$query = "SELECT meta_value FROM wp_postmeta WHERE post_id=your post id AND meta_key='class';    
$results = $wpdb->get_row($query) ;  echo $results->meta_value;   
  • I can try, but I want to understand why the field is saved correctly and not displaayed. – sialfa Nov 16 at 19:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.