Skip to content

Instantly share code, notes, and snippets.

@LeanSeverino1022
Created April 5, 2020 04:31
Show Gist options
  • Save LeanSeverino1022/06629895e6d539117fe87d71f13907ff to your computer and use it in GitHub Desktop.
Save LeanSeverino1022/06629895e6d539117fe87d71f13907ff to your computer and use it in GitHub Desktop.
[Create a new query to run inside your page or template.] #wordpress

All of the above examples showed you how to modify the main query. In many instances, you’ll want to run a separate query to load different information, and leave the main query unchanged. This is where Custom WordPress Queries are useful.

This is best when the content you’re displaying is being loaded in addition to your current page’s content. For instance, if you had a page about Spain and wanted to show your 5 most recent blog posts about Spain at the bottom, you could do something similar to this:

/**
 * Display posts about spain
 *
 */
function be_display_spain_posts() {

  $loop = new WP_Query( array(
    'posts_per_page' => 5,
    'category_name' => 'spain',
  ) );
  
  if( $loop->have_posts() ): 
    echo '<h3>Recent posts about Spain</h3>';
    echo '<ul>';
    while( $loop->have_posts() ): $loop->the_post();
      echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
    endwhile;
    echo '</ul>';
  endif;
  wp_reset_postdata();
}
add_action( 'genesis_after_entry', 'be_display_spain_posts' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment