First time making a custom query. I was looking for a way to get a list of categories for a certain taxonomy so I could run a LIKE query for a autocomplete function. Just to get a few results I came up with the mysql query that gives me results in phpMyAdmin

FROM wp_terms
INNER JOIN wp_term_taxonomy ON ( wp_terms.term_id = wp_term_taxonomy.term_id ) 
WHERE wp_terms.name LIKE  'ca%'
AND count >0
LIMIT 0 , 30

My wordpress function looks like this

function get_categories_by_like_searching() {
    global $wpdb;
    $keyword = $_GET['query']; // example : "ca" would return categories with name of "cats"
    $query = $wpdb->prepare( "SELECT * FROM $wpdb->wp_terms 
                                INNER JOIN $wpdb->wp_term_taxonomy 
                                    ON ($wpdb->wp_terms.term_id = $wpdb->wp_term_taxonomy.term_id) 
                                WHERE $wpdb->wp_terms.name LIKE %s AND $wpdb->wp_terms.count > 0", $wpdb->esc_like($keyword) . '%');
    $categories = $wpdb->query($query);
    foreach($categories as $category) { 
    $results = array("suggestions"=>$results);
    $response = json_encode($results);
    // response output
    header( "Content-Type: application/json" );
    echo $response;

Am I making the connection incorrectly or is my wordpress query syntax off?

The exact function I'm looking for is really this:


$args = array(
    'taxonomy'                 => 'my_custom_taxonomy'
     // with category names LIKE 'x%'

$categories = get_categories($args);

You're including the table prefix, but $wpdb takes care of that.


$query = $wpdb->prepare( "SELECT * FROM $wpdb->wp_terms INNER JOIN $wpdb->wp_term_taxonomy ON ($wpdb->wp_terms.term_id = $wpdb->wp_term_taxonomy.term_id) WHERE $wpdb->wp_terms.name LIKE %s AND $wpdb->wp_terms.count > 0", $wpdb->esc_like($keyword) . '%');


$query = $wpdb->prepare( "SELECT * FROM $wpdb->terms INNER JOIN $wpdb->term_taxonomy ON ($wpdb->terms.term_id = $wpdb->term_taxonomy.term_id) WHERE $wpdb->terms.name LIKE %s AND $wpdb->terms.count > 0", $wpdb->esc_like($keyword) . '%');

(double-check in case I missed any)

  • Found solution, change $wpdb->query($query) to $wpdb->get_results($query)
    – Darius
    Dec 17 '14 at 16:19
  • so it's not the query. what does $categories return? Dec 17 '14 at 16:20
  • 1
    oh, silly me. you're using $wpdb->query which returns the number of rows affected/selected, not the results. try $wpdb->get_results Dec 17 '14 at 16:21
  • Yep, that did the trick :) "get_results", nice to know what $wpdb->query does too, future reference. Thank you.
    – Darius
    Dec 17 '14 at 16:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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