Skip to content

Instantly share code, notes, and snippets.

@kierzniak
Last active June 15, 2018 10:57
Show Gist options
  • Save kierzniak/42b119043a95f8ba7b6aff7dbb26992e to your computer and use it in GitHub Desktop.
Save kierzniak/42b119043a95f8ba7b6aff7dbb26992e to your computer and use it in GitHub Desktop.
Modify raw SQL created by WP Query to order posts by custom wp_posts table column
<?php
/**
* Make sample fake query to show working example
*/
function motivast_wp_query() {
new WP_Query(array(
/**
* This line will not modify your query but we can use it to
* identify query later `$wp_query->get('orderby') === 'custom'`.
*/
'orderby' => 'custom'
));
}
add_action( 'wp', 'motivast_wp_query' );
/**
* Filters the ORDER BY clause of the query.
*
* @param string $orderby The ORDER BY clause of the query.
* @param WP_Query $wp_query The WP_Query instance (passed by reference).
*
* @return string
*/
function motivast_orderby_custom_column( $orderby, $wp_query ) {
/**
* If WP_Query has `custom` as orderby parameter replace SQL
*/
if( $wp_query->get('orderby') === 'custom' ) {
return 'wp_posts.custom DESC';
}
return $orderby;
}
add_filter( 'posts_orderby', 'motivast_orderby_custom_column', 10, 2 );
@waqasy
Copy link

waqasy commented Jun 13, 2018

ok, its working. but it should be $wp_query->get('orderby') since its normal parameter in wp_query

@kierzniak
Copy link
Author

Done, thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment