FacetWP – sort while preserving sticky posts at the top

mgibbs189

{{gist file=”test.php” lang=”php”}}
<?php

function fwp_preserve_sticky_posts( $query ) {
if ( ! empty( $query->query_vars[‘orderby’] ) && ‘post__in’ == $query->query_vars[‘orderby’] ) {
global $wpdb;

$featured_ids = $wpdb->get_col( “SELECT DISTINCT post_id FROM {$wpdb->postmeta} WHERE meta_key = ‘_featured’ AND meta_value = ‘1’” );

$matches = array();
$post_in = (array) $query->query_vars[‘post__in’];
foreach ( $featured_ids as $post_id ) {
if ( false !== ( $pos = array_search( $post_id, $post_in ) ) ) {
$matches[ $pos ] = $post_id;
}
}
ksort( $matches ); // preserve sort order of sticky posts
$query->query_vars[‘post__in’] = array_merge( $matches, $query->query_vars[‘post__in’] );
}
}
add_action( ‘pre_get_posts’, ‘fwp_preserve_sticky_posts’ );
{{/gist}}