Forums

[resolved] Function using custom SQL to return array of specific category ID (2 posts)

  1. Martin Black
    Member
    Posted 6 months ago #

    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.

  2. Martin Black
    Member
    Posted 6 months ago #

    Solved as follows:

    function get_positional_categories() {
    global $wpdb;
    $poscats = $wpdb->get_results("
        SELECT name,term_id FROM <code>wp_terms</code>
        WHERE name LIKE '\_%';
    ");
    $count = 0;
    foreach ($poscats as $pcat) {
        $poscats[$count] = $pcat->term_id;
        $count++;
    }
    return $poscats;
    }

Reply

You must log in to post.

About this Topic