Skip to content

Instantly share code, notes, and snippets.

@jpen365
Created November 26, 2016 16:09
Show Gist options
  • Save jpen365/67592c6e5f70553692a002fea13da63f to your computer and use it in GitHub Desktop.
Save jpen365/67592c6e5f70553692a002fea13da63f to your computer and use it in GitHub Desktop.
Use setup_postdata() to use template tags when using get_posts() to query the database
<?php
$args = array(
'numberposts' = '4',
'category_name' = 'slider'
);
$slider_posts = get_posts( $args );
if ( $slider_posts ) {
foreach ( $slider_posts as $post ) :
// First, setup post data
setup_postdata( $post );
// Second, define content to display ?>
<h2><?php the_title(); ?></h2>
<?php the_content(); ?>
<!--setup_postdata() required for the_title() and the_content() to work--><?php
endforeach;
// Third, reset post data after end of the foreach function
wp_reset_postdata();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment