Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mahdi-alavi/b50e89e9d1564e581a7b228c91872428 to your computer and use it in GitHub Desktop.
Save mahdi-alavi/b50e89e9d1564e581a7b228c91872428 to your computer and use it in GitHub Desktop.
WP_Query orderby include Argument for tax_query (taxonomy)
// Let’s presume we have a ‘product’ post type, with a ‘names’ taxonomy.
/* The posts_orderby filter.
=========================================================================== */
function itl_edit_posts_orderby( $orderby_statement, $wp_query ) {
if ( isset( $wp_query->query['orderby'] ) && 'include' == $wp_query->query['orderby'] ) {
$include = implode( ',', array_map( 'absint', $wp_query->query['include'] ) );
$orderby_statement = "FIELD( term_taxonomy_id, $include )";
}
return $orderby_statement;
}
add_filter( 'posts_orderby', 'itl_edit_posts_orderby', 10, 2 );
/* WP_Query
=========================================================================== */
$ids = array( 28, 27, 30, 29, 22 );
$args = array(
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => 10,
'orderby' => 'include',
'include' => $ids,
'tax_query' => array(
array(
'taxonomy' => 'names',
'field' => 'term_id',
'terms' => $ids,
),
),
);
@Adomph
Copy link

Adomph commented May 19, 2021

Hello, Thanks for your help !
I modified your code to add sub terms after his parent term like this :

function edit_posts_orderby($orderby_statement, $wp_query) {
	if ( isset( $wp_query->query['orderby'] ) && 'include' == $wp_query->query['orderby'] ) {
		$term_ids = array();
								
		foreach($wp_query->query['include'] as $slug) {
			$get_term = get_term_by('term_id', $slug, $taxonomy);
			if($get_term->parent === 0) {
				if(!in_array($get_term->term_id, $term_ids)) {
					$term_ids[] = $get_term->term_id;
				}
			}
			else {
				if(!in_array($get_term->parent, $term_ids)) {
					$term_ids[] = $get_term->parent;
					$term_ids[] = $get_term->term_id;
				}
				else {
					$pos = array_search($get_term->parent, $term_ids) + 1;
					array_splice($term_ids,$pos,0,$get_term->term_id);
				}
			}
		}
		$result = implode( ',', array_map( 'absint', $term_ids) );
		$orderby_statement = "FIELD( term_taxonomy_id, $result)";	
	}
}
add_filter( 'posts_orderby', 'edit_posts_orderby', 10, 2 );

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