Frank Lucas Frank Lucas - 7 months ago 9
PHP Question

Wordpress looping over custom post type and printing out post title

I made a custom post type named

sport
, so I added a couple of sports and queried and printed them out like this:

$sports = new WP_Query(array('post_type'=>'sport','posts_per_page' => -1,));

echo '<pre>';
print_r($sports);
echo '<pre>';
wp_reset_postdata();


Everything's great, my next step is to loop over the sports and print out the title. I tried doing it like so, but I get the error:
undefined index: post_title


<section class="faq paddings">
<div class="container">
<div class="row top-mini">
<?php foreach($sports as $sport): ?>
<div class="col-md-4">
<h3><?php echo $sport['post_title'] ?></h3>
</div>
<?php endforeach; ?>
</div>
</div>
</section>


Anyone could help me out here?

Thanks in advance!!

Raf Raf
Answer

try:

<?php if($sports->have_posts()) : ?>
<section class="faq paddings">
   <div class="container">
    <div class="row top-mini">
    <?php while($sports->have_posts()) :  $sports->the_post(); ?>
      <div class="col-md-4">
         <h3><?php the_title(); ?></h3>
      </div>
  <?php endwhile; ?>
    </div>
  </div>
</section> 
<?php endif; wp_reset_postdata() ?>
Comments