Skip to content

Instantly share code, notes, and snippets.

@emanuellopes
Last active September 28, 2023 14:31
Show Gist options
  • Save emanuellopes/6a53efab8e4e95225949d17783d16c29 to your computer and use it in GitHub Desktop.
Save emanuellopes/6a53efab8e4e95225949d17783d16c29 to your computer and use it in GitHub Desktop.
Orderby posts by typeof content
<?php
class Search {
public function __construct() {
add_filter('posts_orderby', array($this, 'postsOrderBy'), 10, 2);
$result = new PostQuery($args, Post::class);
remove_filter('posts_orderby', array($this, 'postsOrderBy'));
}
public function postsOrderBy(string $orderBy, WP_Query $query): string
{
if (isset($query->query_vars['orderby']) && $query->query_vars['orderby'] === 'sticky') {
/** @var array $stickyPosts */
$stickyPosts = get_option('sticky_posts');
$stickyPosts = array_map(static function ($id) {
return (int) $id;
}, $stickyPosts);
if ($stickyPosts) {
$orderBy = 'CASE WHEN wp_posts.ID IN (' . implode(',', $stickyPosts) . ') THEN 1 ELSE 2 END, wp_posts.post_date DESC';
}
}
return $orderBy;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment