WordPress.org

Ready to get started?Download WordPress

Forums

get_categories by initial name (8 posts)

  1. takien
    Member
    Posted 4 years ago #

    In the wordpress codex of get_categories (http://codex.wordpress.org/Function_Reference/get_categories) it says:

    Arguments are pretty much the same as wp_list_categories and can be passed as either array or in query syntax.

    means that I can put own sql query as args...

    I just want to put something like WHERE name LIKE "A%"
    to retrieve only category with name starting with A letter...

    but how to embed that query to the args...

    thanks...

  2. esmi
    Forum Moderator
    Posted 4 years ago #

    No - it means that you can use the same parameters as wp_list_categories. You can't pass an sql query to either get_categories or wp_list_categories.

  3. takien
    Member
    Posted 4 years ago #

    thanks esmi,
    so what is the simplest way to get what I need..? :)

  4. esmi
    Forum Moderator
    Posted 4 years ago #

    There isn't an easy way to grab just the categories that start with "A". In theory:

    <?php
    $a_cats = array();
    $args=array(
      'orderby' => 'name',
      'order' => 'ASC'
      );
    $categories=get_categories($args);
    foreach($categories as $category) {
    	$first_letter = strpos ($category->name,'A');
    	if ($first_letter === false) break;
    	else $a_cats[] = $category;
    }
    ?>

    might work but I've not tested it. It's purely "off the top of my head".

  5. takien
    Member
    Posted 4 years ago #

    Thanks esmi, nice trick btw :D
    btw your code is not work, it's return empty array...

    i have fixed it
    and now it's work fine using this code..

    foreach($categories as $category) {
    $cat_name = $category->name;
    if(strtolower($cat_name[0]) == strtolower($_GET['start'])) {
    echo $cat_name.'<br />';
    }
    }

    once again, many thanks :)
    I could not figure it out before that it can be that simple. hahahha

  6. esmi
    Forum Moderator
    Posted 4 years ago #

    Sometimes it just helps to have someone else to bounce ideas off. :-)

  7. takien
    Member
    Posted 4 years ago #

    hi again esmi, :D
    i can see your username is linked to your profile http://profiles.wordpress.org/esmi/ , why mine is not?

  8. esmi
    Forum Moderator
    Posted 4 years ago #

    It is now. The link are aren't added automatically and can sometimes take quite a while to appear.

Topic Closed

This topic has been closed to new replies.

About this Topic