Showing a list of Custom Post Type using get_posts() loop in WordPress

Here is how to create a loop for Custom Post Types, it’s really simple and it’s all about the parameter post_type. You can use this code for looping any type of posts (also the default WordPress post types: post and page). Please, use get_posts() for looping posts, and not WP_Query().

// Set the arguments for the query
$args = array( 
  'numberposts'		=> -1, // -1 is for all
  'post_type'		=> 'movie', // or 'post', 'page'
  'orderby' 		=> 'title', // or 'date', 'rand'
  'order' 		=> 'ASC', // or 'DESC'
  //'category' 		=> $category_id,
  //'exclude'		=> get_the_ID()
  // ...

// Get the posts
$myposts = get_posts($args);

// If there are posts
  // Loop the posts
  foreach ($myposts as $mypost):
  <div class="row">
    <!-- Image -->
    <div class="col-xs-3"> 
      <?php getFirstImg($mypost->ID); // Implement this how you want ?>
    <!-- Content -->
    <div class="col-xs-9">
      <h1><a href="<?php echo get_permalink($mypost->ID); ?>"><?php echo get_the_title($mypost->ID); ?></a></h1>
      <?php echo $trimmed = wp_trim_words(get_the_content($mypost->ID), 15, '...'); ?>

  <?php endforeach; wp_reset_postdata(); ?>
<?php endif; ?>
  • Matt Hamer

    Thanks for this; had to use the following as I required the entire post contents to be displayed.
    ID); ?>


Category BootstrapCategory CoffeescriptCategory DrupalCategory GravCategory HTMLCategory JavascriptCategory JoomlaCategory jQueryCategory LaravelCategory MagentoCategory PHPCategory SharePointCategory SpringCategory ThymeleafCategory WordPressCategory Workflow


Developed and designed by Netgloo
© 2019 Netgloo