Skip to content

Instantly share code, notes, and snippets.

@zzap
Created September 30, 2016 18:14
Show Gist options
  • Save zzap/ec0bfd663e74a6a7095852abf663d52c to your computer and use it in GitHub Desktop.
Save zzap/ec0bfd663e74a6a7095852abf663d52c to your computer and use it in GitHub Desktop.
Custom post classes for custom post types based on taxonomies Default 'posts' in WordPress have, among other, classes based on their categories and tags. This function adds post classes to custom post types based on taxonomies.
<?php
/**
* Hook
*/
add_filter( 'post_class' , 'zzap_cpt_post_class' );
/**
* Custom post classes for custom post types based on taxonomies
*
* Default 'posts' in WordPress have, among other, classes
* based on their categories and tags. This function adds
* post classes to custom post types based on taxonomies.
* This function is attached to 'post_class' filter hook.
*
* @param array $classes An array of post classes.
* @return array Returnes filtered post classes
*/
function zzap_cpt_post_class( $classes ) {
global $post;
// get post type
$post_type = get_post_type( get_the_ID() );
// if post type is not 'post' or 'page' - add 'attachment' if you wish
if ( ! in_array( $post_type, array( 'post', 'page' ) ) ) : {
// go to taxonomies array
$post_type_taxonomies = get_object_taxonomies( $post_type );
foreach ( $post_type_taxonomies as $taxonomy ) {
// get all terms for each taxonomy
$terms = get_the_terms( get_the_ID(), $taxonomy );
// if we have any term
if ( ! empty( $terms ) ) {
// loop through each of them
foreach ( $terms as $term ) {
$taxonomy = $term->taxonomy; // this will get taxonomy slug
$slug = $term->slug; // this will get term slug
// finally build our classes in WordPress' default format for categories and tags
$classes[] = $taxonomy . '-' . $slug;
}
}
}
return $classes;
}
endif;
return $classes;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment