I’m having trouble with a PHP script that should pull category titles from my WordPress database. I need to fetch the name “Oranges” from the wp_terms table but my code isn’t working properly.
Here’s what I’m trying:
<?php
$fruit_cat_id = 5;
$category_data = $wpdb->get_results("SELECT name FROM $wpdb->terms WHERE term_id = '5'");
$category_title = $category_data->name;
?>
<h2>Selected Category: <?php echo $category_title; ?></h2>
My database structure looks like this:
term_id name slug term_group
1 General general 0
2 Links links 0
3 Cherries cherries 0
4 Grapes grapes 0
5 Oranges oranges 0
The query runs but doesn’t output the category name. What am I missing in my approach to access the WordPress terms table correctly?
The issue is you’re handling the returned data wrong. get_results() always returns an array of objects, even for single rows. You’re trying to access ->name directly on the array instead of the first element. Since you only want one value, use get_var() instead:
$category_title = $wpdb->get_var("SELECT name FROM $wpdb->terms WHERE term_id = 5");
I also removed the quotes around 5 - it’s better to use the integer directly for numeric comparisons. This returns the string value directly instead of an array, so no more indexing issues.
Had the same issue with WordPress database queries. Skip the raw SQL and use WordPress’s built-in functions instead. Try get_term() like this: $term = get_term($fruit_cat_id); $category_title = $term->name; It’s way safer since it handles caching, applies filters, and won’t break when WordPress updates. Raw queries can fail if WordPress changes its structure, plus you lose all the error handling. The built-in functions are made for exactly this stuff and they’re much more reliable.
your issue is that get_results returns an array, not a single object. try $category_title = $category_data[0]->name; instead. also, get_var works better for single values - it’s cleaner for this type of query.