WordPress category name not showing up with custom MySQL query

Hey folks, I’m scratching my head over this WordPress database issue. I’m trying to fetch a category name using a custom MySQL query, but it’s not working as expected.

Here’s what I’ve got:

$category_id = 3;
$category = $wpdb->get_results("SELECT name FROM $wpdb->terms WHERE term_id = '$category_id'");
$category_name = $category->name;

echo '<h3>Category: ' . $category_name . '</h3>';

The wp_terms table looks like this:

term_id | name          | slug          | term_group
1       | Uncategorized | uncategorized | 0
2       | Blogroll      | blogroll      | 0
3       | Apples        | apples        | 0
4       | Bananas       | bananas       | 0

I’m trying to get ‘Apples’ to show up, but nothing’s displaying. Any ideas what I’m doing wrong here? Is there a better way to fetch category names in WordPress? Thanks in advance for any help!

I’ve encountered similar issues before. The problem lies in how you’re accessing the result. When using get_results(), WordPress returns an array of objects, not a single object. Try modifying your code like this:

$category = $wpdb->get_results(“SELECT name FROM $wpdb->terms WHERE term_id = ‘$category_id’”);
$category_name = $category[0]->name;

This should work. However, for fetching category names, I’d recommend using WordPress functions instead of direct SQL queries. They’re safer and handle caching:

$category_name = get_cat_name($category_id);

This approach is more WordPress-friendly and less prone to errors. It also automatically sanitizes inputs, which is crucial for security.

hey mate, i think ur missing somethin there. instead of get_results, try using get_var(). it’ll give u the value directly:

$category_name = $wpdb->get_var(“SELECT name FROM $wpdb->terms WHERE term_id = $category_id”);

that should do the trick. let me kno if it works for ya!

I’ve dealt with similar category name retrieval issues in WordPress before. While the SQL approach can work, I’ve found it’s often better to use WordPress’s built-in functions for this kind of task. They’re typically more efficient and handle edge cases better.

In your situation, I’d recommend using get_term():

$category = get_term($category_id, ‘category’);
if (!is_wp_error($category)) {
$category_name = $category->name;
echo '

Category: ’ . $category_name . ‘

’;
} else {
echo ‘Category not found’;
}

This method is not only more reliable but also takes advantage of WordPress’s caching mechanisms, which can improve performance, especially if you’re fetching multiple categories. It’s also safer as it handles potential errors gracefully.

Just remember to sanitize your $category_id input if it’s coming from user input to prevent any potential security issues.