query posts with selected post ids first

Is there a way I can get most recent posts with a couple of posts I specify by post ID listed first?

According the docs, the order and orderby parameters may be passed as an array, so in theory I'm wondering if this could be possible.

In MySQL query terms, it would essentially produce a result like

SELECT * FROM wp_posts ORDER BY ID=12345 desc, ID=12543 desc, post_date desc

where it returns post 12345, then 12543, then the rest ordered newest first.

Topic order wp-query posts Wordpress

Category Web


I'm not sure if it's possible to do this in a single query in Wordpress. You could potentially split it into two like below:

<ul>
<?php
global $post;

// Get posts by selected post ids
$args = array(
    'posts_per_page' => -1,
    'post__in'       => [12345,12543],
    'orderby'        => 'post__in'
);
$myposts = get_posts($args);
foreach ($myposts as $post) : setup_postdata($post); ?>
    <li>
    <?php echo get_the_ID(); ?>
    </li>
<?php endforeach;
wp_reset_postdata();

// Get latest posts excluding selected post ids
$args = array(
    'posts_per_page' => -1,
    'exclude'        => [12345,12543]
);

$myposts = get_posts($args);
foreach ($myposts as $post) : setup_postdata($post); ?>
    <li>
    <?php echo get_the_ID(); ?>
    </li>
<?php endforeach;
wp_reset_postdata();
?>
</ul>

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.