Created
December 16, 2020 22:40
-
-
Save heyjones/a807201da0accba2db46e9b3eca9bedc to your computer and use it in GitHub Desktop.
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 | |
namespace wp_orderby_termmeta; | |
add_action( 'posts_fields', __NAMESPACE__ . '\\posts_fields', 10, 2 ); | |
add_action( 'posts_orderby', __NAMESPACE__ . '\\posts_orderby', 10, 2 ); | |
// Append the "sort" column to the query... | |
function posts_fields( $fields, $query ) { | |
if( 'art' == $query->query_vars['post_type'] ) { | |
global $wpdb; | |
$fields .= ', IFNULL( ( SELECT ' . $wpdb->termmeta . '.meta_value FROM ' . $wpdb->termmeta . ' INNER JOIN ' . $wpdb->terms . ' ON ' . $wpdb->termmeta . '.term_id = ' . $wpdb->terms . '.term_id INNER JOIN ' . $wpdb->term_taxonomy . ' ON ' . $wpdb->terms . '.term_id = ' . $wpdb->term_taxonomy . '.term_id INNER JOIN ' . $wpdb->term_relationships . ' ON ' . $wpdb->term_taxonomy . '.term_taxonomy_id = ' . $wpdb->term_relationships . '.term_taxonomy_id WHERE ' . $wpdb->term_relationships . '.object_id = ' . $wpdb->posts . '.ID AND ' . $wpdb->termmeta . '.meta_key = "sort" AND ' . $wpdb->term_taxonomy . '.taxonomy = "art_type" LIMIT 1), 0) AS `sort` ' ; | |
} | |
return $fields; | |
} | |
// ... then, sort by it. | |
function posts_orderby( $orderby, $query ) { | |
if( 'art' == $query->query_vars['post_type'] ) { | |
$orderby = '`sort` ASC, ' . $orderby; | |
} | |
return $orderby; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment