Skip to content

Instantly share code, notes, and snippets.

@tomjn
Last active February 26, 2021 21:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomjn/7faaca9b78310f51c6bbe2391af0337b to your computer and use it in GitHub Desktop.
Save tomjn/7faaca9b78310f51c6bbe2391af0337b to your computer and use it in GitHub Desktop.
<?php
function exclude_post_categories( $exclude = '', $spacer = ' ' ) {
$categories = get_the_category();
if ( empty( $categories ) ) {
return;
}
$exclude = explode( ',', $exclude );
$counter = count( get_the_category() ) - count( $exclude );
foreach ( $categories as $cat ) {
$counter--;
if ( in_array( $cat->cat_ID, $exclude, true ) ) {
continue;
}
?>
<a
href="<?php echo esc_url( get_category_link( $cat->cat_ID ) ); ?>"
title="<?php echo esc_attr( $cat->cat_name ); ?>"
>
<?php echo esc_html( $cat->cat_name ); ?>
</a>
<?php
if ( 0 === $counter ) {
echo $spacer;
}
}
}
@tomjn
Copy link
Author

tomjn commented Feb 26, 2021

Taken and improved from https://css-tricks.com/snippets/wordpress/the_category-excludes/:

  • fixed a bug where $post was used but never declared
  • fixed security bugs due to lack of escaping
  • applied WP coding standards
  • reduced cyclomatic and NPath complexity
  • checks now exit early
  • eliminated early escaping by outputting directly and escaping on output
  • the exclude argument was renamed to make more sense in PHP 8.0 when using named arguments

@tomjn
Copy link
Author

tomjn commented Feb 26, 2021

lowhanging fruit, wp_parse_str or wp_parse_args could allow the exclusion parameter to be both "1,2,3" or [1,2,3]

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