Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I'm developing a custom theme which uses categories for positioning, all of which begin with an underscore (e.g. _position1). I have an SQL query as below to get a list of these categories (those starting with an underscore).

SELECT name,term_id FROM `wp_terms`
WHERE name LIKE '\_%';

How would I go about turning this into a function which returns a list of the category IDs?

The idea being that this list of IDs can be passed to wp_list_categories() to be excluded e.g. (where get_positional_ids would use the SQL above to return a list of IDs)

<?php 
$excludeids = get_positional_ids();
$args = array('exclude'=> $excludeids);
wp_list_categories($args); 
?>

Any ideas on how to do this? Thanks.

share|improve this question
add comment

2 Answers

up vote 1 down vote accepted

If you use the built in get_terms function you end up with a quick one liner:

function get_positional_ids(){
    return get_terms( 'category', array('fields' => 'ids', 'name__like' => '_'));
}

no custom SQL, safe and simple.

share|improve this answer
    
Worked, Thanks! –  MartinB Nov 13 '11 at 22:17
add comment

A better idea would be to create a custom taxonomy as 'Positions', and put all your position values under this taxonomy. It will be easier to handle this than to write custom SQL. But if you still want to go with the SQL way, try this...

<?php
function get_positional_ids()
{
    global $wpdb;
    $pos_query = SELECT term_id FROM `wp_terms` WHERE name LIKE '\_%';

    //This will return an array of objects with the values returned by the query
    $pos_id_objs = $wpdb->get_results($pos_query);
    $pos_ids = array();

    //we loop through the array of objects and form an array of ids we want to return
    foreach($pos_id_objs as $pos_id_obj)
    {
        $pos_ids[] = $pos_id_obj->term_id;
    }

    return $pos_ids;
}

Put this in functions.php Haven't tested, but should work. Check out the doc for $wpdb class.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.