Last active
June 15, 2018 10:57
-
-
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
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 | |
/** | |
* 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 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ok, its working. but it should be
$wp_query->get('orderby')
since its normal parameter in wp_query