I am using this code to show a custom post type (named ‘videos’) in an archive page template. The problem is, it only shows 1 result – the most recent post – even though I have 20 posts.
How do I get this to show ALL posts in this custom post type instead of just one?
<?php
$posts = get_posts(array(
'post_type' => 'videos',
'posts_per_page' => -1
));
if( $posts ): ?>
<?php foreach( $posts as $post ):
setup_postdata( $post );
?>
<?php echo wp_oembed_get( get_field( 'video_youtube_url' ) ); ?>
<h1 class="title"><?php the_title(); ?></h1>
<?php
$posts = get_field('video_artist_name');
if( $posts ): ?>
<?php foreach( $posts as $post): ?>
<?php setup_postdata($post); ?>
<a href="<?php the_permalink(); ?>">
<div class="artist-name"><?php the_title(); ?></div>
</a>
<?php endforeach; ?>
<?php wp_reset_postdata(); ?>
<?php endif; ?>
<?php endforeach; ?>
<?php wp_reset_postdata(); ?>
<?php endif; ?>
Hi @lowercase
I believe it was because you used the $posts
variable multiple times before the loop is finished. Could you please try the following code instead?
<?php
$posts = get_posts(array(
'post_type' => 'videos',
'posts_per_page' => -1
));
if( $posts ): ?>
<?php foreach( $posts as $post ):
setup_postdata( $post );
?>
<?php echo wp_oembed_get( get_field( 'video_youtube_url' ) ); ?>
<h1 class="title"><?php the_title(); ?></h1>
<?php
$posts2 = get_field('video_artist_name');
if( $posts2 ): ?>
<?php foreach( $posts2 as $post): ?>
<?php setup_postdata($post); ?>
<a href="<?php the_permalink(); ?>">
<div class="artist-name"><?php the_title(); ?></div>
</a>
<?php endforeach; ?>
<?php wp_reset_postdata(); ?>
<?php endif; ?>
<?php endforeach; ?>
<?php wp_reset_postdata(); ?>
<?php endif; ?>
I hope this helps.
Thank you so much James. We have been trying to work this one out for a while and you have managed to to nail the answer perfectly!