Last active
September 28, 2023 14:31
-
-
Save emanuellopes/6a53efab8e4e95225949d17783d16c29 to your computer and use it in GitHub Desktop.
Orderby posts by typeof content
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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