The most appropriate use for get_posts is to create an array of posts based on a set of parameters. It retrieves a list of latest posts or posts matching the criteria. If you would like to alter the main query before it is executed, you can hook into it using pre_get_posts
.
If you would just like to call an array of posts based on a small and simple set of parameters within a page, then get_posts is your best option.
Create a custom template page and simply paste this snippet there:
1 2 3 4 5 6 7 8 9 10 11 |
<?php query_posts(array('orderby' => 'rand', 'showposts' => 1)); if (have_posts()) : while (have_posts()) : the_post(); ?> <h1><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h1> <?php the_content(); ?> <?php endwhile; endif; ?> |
Use below code to show the latest ten posts sorted alphabetically in ascending order. The following code will display their post date, title and post descriptions:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?php $args = array( 'posts_per_page' => 10, 'order'=> 'ASC', 'orderby' => 'title' ); $postslist = get_posts( $args ); foreach ( $postslist as $post ) : setup_postdata( $post ); ?> <div> <?php the_date(); ?> <br /> <?php the_title(); ?> <?php the_excerpt(); ?> </div> <?php endforeach; wp_reset_postdata(); ?> |
Use the below code inside the wordpress loop function:
1 2 3 4 5 6 7 8 9 10 11 12 |
<?php $args = array( 'post_type' => 'attachment', 'posts_per_page' => -1, 'post_status' =>'any', 'post_parent' => $post->ID ); $attachments = get_posts( $args ); if ( $attachments ) { foreach ( $attachments as $attachment ) { echo apply_filters( 'the_title' , $attachment->post_title ); the_attachment_link( $attachment->ID , false ); } } ?> |
If you want to get the slug of your recent post,then simply copy & paste this code:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?php $the_slug = 'my-slug'; $args=array( 'name' => $the_slug, 'post_type' => 'post', 'post_status' => 'publish', 'posts_per_page' => 1 ); $my_posts = get_posts( $args ); if( $my_posts ) { echo 'ID on the first post found ' . $my_posts[0]->ID; } ?> |
Want to access all post’s data including the attachments,description,title,date,featured images etc. use the below code. This is resolved by calling an internal function setup_postdata(),
with the $post array as its argument:
1 2 3 4 5 6 7 8 9 |
<?php $args = array( 'posts_per_page' => 3 ); $lastposts = get_posts( $args ); foreach ( $lastposts as $post ) : setup_postdata( $post ); ?> <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> <?php the_content(); ?> <?php endforeach; wp_reset_postdata(); ?> |
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.
Article Tags: access post data, Displays Random Posts, how to access all post data, Latest posts ordered by title, ordered posts by title, wordpress, wordpress post data, wordpress random posts