Can I get the term by it's id without knowing to which taxonomy it belongs?
I have a meta field that stores term names, but doesn't store the taxonomy. However, all the get_term()
function have taxonomy parameter marked as required.
Maybe I can get the taxonomy of the term by it's (the term's) name somehow?
I'm trying:
$term_names = ['red','blue'];
$term_datas = $wpdb->get_row( $wpdb->prepare(
"SELECT t.* FROM $wpdb->terms AS t WHERE t.name = $term_names"
) );
var_dump($term_datas);
Can I get the term by it's id without knowing to which taxonomy it belongs?
I have a meta field that stores term names, but doesn't store the taxonomy. However, all the get_term()
function have taxonomy parameter marked as required.
Maybe I can get the taxonomy of the term by it's (the term's) name somehow?
I'm trying:
$term_names = ['red','blue'];
$term_datas = $wpdb->get_row( $wpdb->prepare(
"SELECT t.* FROM $wpdb->terms AS t WHERE t.name = $term_names"
) );
var_dump($term_datas);
Share
Improve this question
edited Nov 5, 2019 at 9:56
entreprenerds
1834 bronze badges
asked Sep 28, 2019 at 14:45
hungryhotdoghungryhotdog
1
5
- Your meta field should store the term ID, not the name. Storing names is a bad idea when IDs are available. Everything but the ID is subject to change. – Jacob Peattie Commented Sep 28, 2019 at 14:47
- Thanks. I want to search by term_name this time. – hungryhotdog Commented Sep 28, 2019 at 16:44
- This is because we want to search which Taxonomy and term_id from the input term_name. – hungryhotdog Commented Sep 28, 2019 at 16:48
- Term name is ambiguous even within same taxonomy. Traffic patrol officer to the other: Stop the white car! Which of tehm? The white! You are doing it wrong. Can't be solved properly. All you an get is one or more of the term(s) with that name. – Knut Sparhell Commented Sep 29, 2019 at 19:51
- The same term_name does not exist.So I want to search by term_name. – hungryhotdog Commented Sep 30, 2019 at 16:40
1 Answer
Reset to default 0The get_term()
function does not accept a string or array; it only accepts an ID, a stdClass object or a WP_Term object. So I think you're headed in the right direction using $wpdb
. But the SQL query can't accept a PHP array. So try this:
$term_names = ['red','blue'];
$term_names_str = implode(', ', $term_names);
$term_datas = $wpdb->get_results( $wpdb->prepare(
"SELECT * FROM $wpdb->terms WHERE name IN ($term_names_str)"
) );
var_dump($term_datas);
Note, you were using the get_row
method, which would only retrieve one result; get_results
will retrieve all results rows matching the query.