We have a wordpress site and we want, on the archives page for a custom post type, to force a certain post to the top all the time.
We are using ‘pre_get_posts’ in functions.php to edit the sql.
Directly in MySQL we can use:
… ORDER BY CASE WHEN ID = 7075 THEN 0 ELSE 1 END
But we cant get that ‘order by’ clause called from functions.php
(We are dumping the sql statement to the page to see how its processed)
$query->set( ‘orderby’, ‘ CASE WHEN ID = 7075 THEN 0 ELSE 1 END ‘ );
(this gets changed to ‘…ORDER BY wp_posts.ID DESC’)
$query->set( ‘orderby’, ‘ (ID = 7075) ‘ );
$query->set( ‘order’, ‘DESC’ );
(this gets ignored and the default is used ‘… ORDER BY wp_posts.post_date DESC ‘)
$query->set( ‘orderby’, array( ‘CASE WHEN wp_posts.ID = 7075 THEN 1 ELSE 2 END’ => ‘ASC’) );
(no order by clause at all with this one)
Has anyone managed to do this before?
We’d like to not write custom sql for the page.
Any help appreciated 🙂
Read more here: wordpress: force record to top before the rest