Last active
June 5, 2021 18:31
-
-
Save gsgoraya/a2150e21129d506b3a3f0990181dbb7e to your computer and use it in GitHub Desktop.
grouping posts by categories for FilterWP display
This file contains 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 | |
class FWSP_Group_Sub_Cats { | |
public static $last_cat; | |
public static function init() { | |
self::$last_cat = false; | |
add_filter('posts_orderby', array( __CLASS__, 'fwsp_orderby_cat' ), 10, 2); | |
add_action('the_post', array( __CLASS__, 'fwsp_add_cat_seperator' ), 10, 2); | |
add_filter( 'get_terms', array( __CLASS__, 'fwsp_filterout_subcats' ), 10, 2 ); | |
} | |
/* Ordering by a taxonomy, specifically, when the query is being made for 'post' post type, and is a taxonomy query */ | |
public static function fwsp_orderby_cat( $orderby_statement, $wp_query ) { | |
if ($wp_query->get( 'post_type' ) === 'post' && $wp_query->get( 'tax_query' ) ) { | |
$orderby_statement = "wp_term_relationships.term_taxonomy_id ASC, ".$orderby_statement; | |
} | |
return $orderby_statement; | |
} | |
/* This function inserts seperators among the grid items, with the category name that the post belongs to. */ | |
public static function fwsp_add_cat_seperator( $post, $wp_query ) { | |
if ($wp_query->get( 'post_type' ) === 'post' && $wp_query->get( 'tax_query' ) ) { | |
$terms = get_the_terms( $post, 'category' ); | |
// assuming, there is only one category | |
if( ! empty( $terms[0] ) && ( empty( self::$last_cat ) || self::$last_cat !== $terms[0]->slug ) ) { | |
self::$last_cat = $terms[0]->slug; | |
echo "<div class='fwsp_cat_seperator'><h3>".$terms[0]->name."</h3></div>"; | |
} | |
} | |
} | |
public static function fwsp_filterout_subcats( $terms, $taxonomy ) { | |
if( count($taxonomy) === 1 && 'category' === $taxonomy[0] ) { | |
$terms = array_filter( $terms, function( $term ) { | |
return !$term->parent; | |
} ); | |
} | |
return $terms; | |
} | |
} | |
FWSP_Group_Sub_Cats::init(); |
This file contains 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
.fwsp_cat_seperator { | |
flex-basis: 100% !important; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment