WordPress.org

Support

Support » How-To and Troubleshooting » Excluding categories by slug from the Category Widget

Excluding categories by slug from the Category Widget

  • 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");
    ?>
Viewing 5 replies - 1 through 5 (of 5 total)
  • Michael

    @alchymyth

    Forum Moderator

    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

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

    Michael

    @alchymyth

    Forum Moderator

    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");

    @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!

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

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Excluding categories by slug from the Category Widget’ is closed to new replies.
Skip to toolbar