WordPress get_posts Examples

Get the latest posts

$args = array(
  'numberposts' => 10
);

$latest_posts = get_posts( $args );

Get the latest posts from custom post type

$args = array(
  'numberposts' => 10,
  'post_type'   => 'events'
);

$latest_posts = get_posts( $args );

Get all published posts of all post types

$posts = get_posts( array(
  'post_type' => get_post_types(),
  'post_status' => 'publish',
  'numberposts' => -1,
) );

Get latest posts ordered by title

$args = array(
    'posts_per_page' => 10,
    'order'          => 'ASC',
    'orderby'        => 'title'
);

$latest_posts = get_posts( $args );

Get random posts

$args = array(
        'posts_per_page' => 10,
        'orderby'        => 'rand'
);

$random_posts = get_posts( $args );

Get popular posts

$args = array(
  'posts_per_page' => 10,
  'orderby'   => 'comment_count'
);

$popular_posts = get_posts( $args );

Leave a Reply

Your email address will not be published. Required fields are marked *