Skip to content

Instantly share code, notes, and snippets.

@Sstobo
Created November 15, 2017 19:20
Show Gist options
  • Save Sstobo/54938361013dc00ac7ce28cd1f582403 to your computer and use it in GitHub Desktop.
Save Sstobo/54938361013dc00ac7ce28cd1f582403 to your computer and use it in GitHub Desktop.
[WP Custom post loops] #wp #php #posts #post-loops
Use WP_Query when you need to create a paginated query
Use get_posts() to create static, additional loops (e.g. a list of a few recent posts on a homepage, etc.)
############## DEFAULT LOOP
<?php if ( have_posts() ) : ?>
<?php while ( have_posts() ) : the_post(); ?>
<h2><?php the_title(); ?></h2> ###### POST TITLE
<?php the_content(); ?> ###### POST CONTENT
<?php endwhile; ?>
<?php the_posts_navigation(); ?> ##### GETS NAV INFO
<?php else : ?>
<h2>Nothing found!</h2>
<?php endif; ?>
############### TO MODIFY LOOP / MAKE QUERYS
<?php
$args = array( 'post_type' => 'product', 'order' => 'ASC' ); ######## WHAT SPECIFICLY TO PULL
$products = new WP_Query( $args ); // instantiate our object ########
?>
<?php if ( $products->have_posts() ) : ?>
<?php while ( $products->have_posts() ) : $products->the_post(); ?> ######### IF THERE ARE POSTS/ POST
<?php /* ############ Content of the queried post results goes here */ ############# ?>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
<?php else : ?>
<h2>Nothing found!</h2>
<?php endif; ?>
############### GET_POSTS . BEST PRACTICE ####################
We pass $args into get_posts() just like we do WP_Query, but we handle the output a bit differently:
<?php
$args = array( 'post_type' => 'product', 'order' => 'ASC' );
$product_posts = get_posts( $args ); // returns an array of posts
?> ############# POSTS IS THE ITERANT DATA
<?php foreach ( $product_posts as $post ) : setup_postdata( $post ); ?>
#EG: "<H2> {$POST} </H2>'
<?php /* Content from your array of post results goes here */ ?>
<?php endforeach; wp_reset_postdata(); ?>
############## THE ARGUMENTS ARE THE KEY
$args = array(
'order' => 'ASC',
'posts_per_page' => 8,
'post_type' => 'product',
'tax_query' => array(
array(
'taxonomy' => 'product-type',
'field' => 'slug',
'terms' => 'bread',
),
),
);
$products = new WP_Query( $args );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment