Forums

List categories starts with A* (5 posts)

  1. atdheh
    Member
    Posted 2 months ago #

    Hello,

    I have a lyrics site, so I have a lot of categories.
    I have pages A, B, C...
    Example: How to list categories that starts with A*

    Thank you.

  2. MichaelH
    moderator
    Posted 2 months ago #

    <?php
    //list categories if begin with letter a/A
    $categories=get_categories();
    if ($categories) {
      foreach($categories as $category) {
        if ( strtoupper(substr($category->name,0,1)) =='A' ) {
          echo '<p><a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a></p> ';
        }
      }
    }
    ?>
  3. t31os_
    Member
    Posted 2 months ago #

    Michael you'll get faster results with get_terms (it's thousandths of a second, but it's 5-9 times faster)..

    $categories = get_terms('category', 'name__like=a%');
    //$categories = get_terms('category', 'name__like=A%');
    if ($categories) {
    	foreach($categories as $category) {
    		echo '<p><a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a></p> ';
    	}
    }

    Took your code and switched to get_terms...
    name__like paramter is perfect for this case to..

  4. MichaelH
    moderator
    Posted 2 months ago #

    Thanks Mark. I will try to remember that ;)

  5. gcarson
    Member
    Posted 2 weeks ago #

    What would be the code to see if it starts with a number? i tried name__like= 'num' or 'number' but it didn't seem to work. Any thoughts?

Reply

You must log in to post.

About this Topic