Frank Lucas
Frank Lucas

Reputation: 592

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!!

Upvotes: 0

Views: 497

Answers (2)

nigelheap
nigelheap

Reputation: 56

Using the foreach loop you had before you should be able to display the title like so

echo $sport->post_title;

The post is an object.

Upvotes: 0

Raf
Raf

Reputation: 352

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() ?>

Upvotes: 1

Related Questions