Skip to content

Instantly share code, notes, and snippets.

@patric-boehner
Created December 1, 2017 07:45
Show Gist options
  • Save patric-boehner/cee80c56b4d59ee2c141143efb7f8f3a to your computer and use it in GitHub Desktop.
Save patric-boehner/cee80c56b4d59ee2c141143efb7f8f3a to your computer and use it in GitHub Desktop.
Order Search Results by Post Type
<?php
/**
* This is copied from Know The Code's
* KTC-Child Theme
* @source: https://github.com/KnowTheCode/KTC-Child-Theme/blob/master/lib/structure/search.php
* Mostly so i can find it in the future
*/
add_filter( 'posts_orderby', __NAMESPACE__ . '\add_orderby_for_search_query', 50 );
/**
* Add the ORDER BY for the Search Query.
*
* @since 1.5.0
*
* @param string $orderby_sql
*
* @return string
*/
function add_orderby_for_search_query( $orderby_sql ) {
if ( ! is_search() ) {
return $orderby_sql;
}
global $wpdb;
$post_type_order = array(
'lab',
// 'challenge',
// 'explained',
'post',
'docx',
'glossary',
'help-center',
'page',
);
$sql_query = "CASE {$wpdb->posts}.post_type";
foreach( $post_type_order as $order => $post_type ) {
$sql_query .= " WHEN '{$post_type}' THEN " . ( $order + 1 );
}
$sql_query .= ' END';
return $sql_query;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment