[tabgroup]
[tab title=“English“]
System: WordPress
Files used: function.php
Filter used: the_category
Usage: Place the code into functions.php. I recommend to use a child theme. Always!
Result: Child categories are not listed where template tag the_category is used in the theme.[/tab]
[tab title=“Deutsch“]
System: WordPress
Datei: function.php
Filter: the_category
Anwendung: Code in die Datei functions.php kopieren. Ich empfehle dazu immer ein child theme zu benutzen.
Resultat: Unterkategorien werden nicht mehr angezeigt wenn die Funktion the_category im Theme aufgerufen wird.
[/tab]
[/tabgroup]
function show_only_parents($original_data) { /*** * This function filters all child categories from post categories * by filtering the output of template tag 'the_category' * * @param string $original_data (passed by filter) * * @return string ***/ /*** * First we need to make sure we don't mess up the * 'Categories' block in the admin panels / edit post screen * It just worked by returning the original data * * TODO: Keep an eye on different parts of WordPress * as we might interfere with other pages... * * DISCLAIMER: I'm not quite sure what is happening in the admin * area, but passing through the original data helped. ***/ if ( is_admin()) { return $original_data; } else { /*** * Get all categories for the current blog post * I assume this only works when in the_loop. * But moreso the_category should do so as well ***/ $categories = get_the_category(); /*** * Define an empty $output var to suppress php warnings ***/ $output = ""; /*** * Loop through every category and add it to the output var * by checking it has no parents. No parents means it's not child. * Add some funky separator ',' and remove the last one * on return. ***/ foreach( $categories as $category ) { $category_link = get_category_link($category->cat_ID); if ( $category->category_parent == 0) { $output .= '<a title="' . $category->name . '" href="' . $category_link . '">' . $category->name . '</a>, '; } } return rtrim($output, ', '); } } add_filter('the_category', 'show_only_parents');
I copied and pasted this and it worked FLAWLESSLY. Thank you SO MUCH for sharing this!!!! 🙂
Superb! Thank you.