Skip to content

Instantly share code, notes, and snippets.

@krstivoja
Last active April 21, 2023 07:40
Show Gist options
  • Save krstivoja/735301cfd36411376cda27156543ea62 to your computer and use it in GitHub Desktop.
Save krstivoja/735301cfd36411376cda27156543ea62 to your computer and use it in GitHub Desktop.
Sidebar categories list inside Admin Posts
add_action( 'admin_notices', 'add_html_and_category_filter' );
function add_html_and_category_filter() {
$current_screen = get_current_screen();
if ( $current_screen->id === 'edit-post' && $current_screen->post_type === 'post' ) {
$categories = get_categories();
$current_category_id = isset( $_GET['cat'] ) ? intval( $_GET['cat'] ) : 0;
ob_start();
?>
<div id="category-filter-list">
<h2><?php esc_html_e( 'Categories:' ); ?></h2>
<ul>
<li <?php if ( 0 === $current_category_id ) : ?>class="active"<?php endif; ?>>
<a href="<?php echo esc_url( admin_url( 'edit.php?post_status=all&post_type=post' ) ); ?>"><?php esc_html_e( 'All Posts' ); ?></a>
</li>
<?php foreach ( $categories as $category ) : ?>
<?php
$category_link = esc_url( get_category_link( $category->cat_ID ) );
$category_id = $category->cat_ID;
$category_count = $category->count;
?>
<li <?php if ( $category_id === $current_category_id ) : ?>class="active"<?php endif; ?>>
<a href="<?php echo esc_url( admin_url( 'edit.php?s&post_status=all&post_type=post&action=-1&m=0&cat=' . $category_id . '&filter_action=Filter&paged=1&action2=-1' ) ); ?>"><?php echo esc_html( $category->name ); ?> (<?php echo esc_html( $category_count ); ?>)</a>
</li>
<?php endforeach; ?>
</ul>
</div>
<style>
#category-filter-list {
position: absolute;
padding-top: 10px;
left: 0;
width: 200px;
height: 100%;
z-index: 100;
}
#category-filter-list a {
display: block;
padding: 8px 0;
font-size: 14px;
border-bottom: 1px solid lightgray;
text-decoration: none;
}
#category-filter-list li.active a {
font-weight: bold;
}
.wrap{
padding-left: 220px;
}
</style>
<?php
$output = ob_get_clean();
echo $output;
}
}
@krstivoja
Copy link
Author

Here is the preview of the result

Screenshot 2023-04-11 at 09 15 39

@krstivoja
Copy link
Author

Updated code:

  • Changed title to "Categories:"
  • Removed description text
  • Fixed overlap when user open "Screen options"
  • Added active class selected category (Styled as bold)
  • Added numbed of posts for category
  • Added all categories like reset filter

Screenshot 2023-04-13 at 09 30 24

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