Sort custom post type by ID ascending – WordPress

Suppose you have custom post type in WordPress that you want to sort such that it displays the first created post on top. By default, WordPress sort the posts by ID in descending. That means that the latest uploaded post will be displayed on top, which is good in many cases. But there might be a scenario where you want the first post to be displayed first. In this post, we will teach you how to do it using our Social Network API custom post type.

First, you need to go to your WordPress admin panel and navigate to Appearance -> Theme File Editor. In that page, select your current theme and find it’s “index.php” file and open it. In this file, search for a code:

<?php if ( have_posts() ) : ?>

Inside this “if” condition, and before the while loop:

<?php while ( have_posts() ) : the_post(); ?>

Write the following code, make sure to replace “social-network-api” with your own custom post type where you want to apply this sort.

<?php if ( have_posts() ) : ?>
                        
    <?php
        $post_type = $_GET["post_type"] ?? "";
        if ($post_type == "social-network-api"):
            query_posts([
                "post_type" => $post_type,
                "posts_per_page" => 10,
                "orderby" => "ID",
                "order" => "ASC"
            ]);
        endif;
    ?>

    <?php while ( have_posts() ) : the_post(); ?>

    <?php endwhile; ?>

<?php endif; ?>

If you refresh the page now, you will see your first post be displayed first.