Change Post Class function
-
19-12-2020 - |
Question
I wish to change/remove parts of the automatic post class function that's built in to wordpress, lets say when i make a post, the html code generated looks like this:
<div id="post-106" class="contentmain fullwidth post-106 post type-post status-publish format-standard has-post-thumbnail hentry category-test category-test2 category-test3 category-test4 tag-testingtags1 tag-testingtags2 tag-testingtags3">
I wish to remove tags from being in this auto generated code (the tag-testingtags1,2,3), i cannot find which function in wordpress generates the code, anyone care to point me in the right direction? If it is a core file is there a simple way to exclude tags from being inserted into the code using some kind of filter hook in functions.php so i don't have to modify wp core files?
Solution
post_class()
is a wrapper around get_post_class()
.
Try the following hook post_class
which is fired from get_post_class()
within wp-includes/post-template.php
:
add_filter('post_class', 'filter_post_class', 10, 3);
function filter_post_class($classes, $class, $post_id) {
$temp = implode(' ', $classes);
$temp = preg_replace('/\s\btag\-\w*\b/i', '', $temp);
return explode(' ', $temp);
}
Alternatively (RECOMMENED):
add_filter('post_class', 'filter_post_class', 10, 3);
function filter_post_class($classes, $class, $post_id) {
$classes = array_filter($classes, function($class_name){
// use !== 0 to ensure we match tag- at begining of string
return strpos($class_name, 'tag-') !== 0;
});
return $classes;
}
Another alternative method, although potentially with risks, is to:
add_filter('get_the_tags', 'filter_get_the_tags');
function filter_get_the_tags() {
return array();
}
Although with this approach some conditional logic should be considered within the callback.
I say that for the latter because the only other function (in terms of core WP) that calls get_the_tags()
is wp-includes/feed.php
and inparticular get_the_category_rss()
.
OTHER TIPS
You can use the post_class
filter to modify the output of post classes:
add_filter( 'post_class', 'cyb_post_class' );
function cyb_post_class( $classes ) {
// Modify the array $classes as you wish
// For example: remove tag-testingtags1 class
unset( $classes['tag-testingtags1'] );
return $classes;
}
The classes with names starting with tag-
are generated form the tags associated with the post (post tag taxonomy from core). If you want to auto-remove those classes:
add_filter( 'post_class', 'cyb_post_class', 10, 3 );
function cyb_post_class( $classes, $class, $post_id ) {
// Get all the tags associated with the post
$tags = get_the_tags( $post_id );
if( ! is_wp_error( $tags ) ) {
foreach( $tags as $tag ) {
if( isset( $classes['tag-' . $tag->slug] ) ) {
unset( $classes['tag-' . $tag->slug] );
}
}
}
return $classes;
}