WordPress.org

Forums

Excluding categories by slug from the Category Widget (6 posts)

  1. specialmachine
    Member
    Posted 1 year ago #

    I have this bit of code that works wonderfully well for removing categories from the sidebar category widget. However, I can only use IDs and I would much rather have it use the category slug. I'm not a developer, and I've wasted a good few hours hacking around trying to make it work with other code i have that uses slugs for things, but I just don't know enough to get there. If anyone could help, that would be fabulous, and I believe this could be quite useful to others as well.

    <?php
    function exclude_widget_categories($args){
    $exclude = "1"; // The IDs of the excluding categories
    $args["exclude"] = $exclude;
    return $args;
    }
    add_filter("widget_categories_args","exclude_widget_categories");
    ?>
  2. alchymyth
    Forum Moderator
    Posted 1 year ago #

    get_term_by()
    http://codex.wordpress.org/Function_Reference/get_term_by

    example:

    $cat = get_term_by( 'slug', 'slug-to-exclude', 'category' );
    $exclude = $cat->term_id; // The IDs of the excluding categories
  3. specialmachine
    Member
    Posted 1 year ago #

    Wonderful. That works extremely well. Can I bother you to ask how I would exclude multiple categories in that snippet?

  4. alchymyth
    Forum Moderator
    Posted 1 year ago #

    function exclude_widget_categories( $args ){
    
    $excludes = array( 'slug-1', 'cat-slug2', 'another-catslug' ); //array with category slugs to be excluded
    $cat_ids = array();
    foreach( $excludes as $cat_slug ) {
      $cat = get_term_by( 'slug', $cat_slug, 'category' );
      if( $cat ) $cat_ids[] = $cat->term_id;
    }
    $exclude = implode( ',', $cat_ids ); // The IDs of the excluding categories
    if( $cat_ids ) $args["exclude"] = $exclude;
    
    return $args;
    }
    
    add_filter("widget_categories_args","exclude_widget_categories");
  5. specialmachine
    Member
    Posted 1 year ago #

    @alchymyth - I wish I could do something for you. You help me often and always exactly what I need. It's really something. Thank you, thank you, thank you!

  6. studioactiv8
    Member
    Posted 1 year ago #

    this still works..good stuff thanks! Aug 7 2013

Topic Closed

This topic has been closed to new replies.

About this Topic