get term id from term name
-
20-05-2021 - |
Question
Hi i am trying to get term id from term name (title ).
<?php
if ($_SERVER["REQUEST_METHOD"] == "GET") {
// collect value of input field
$nameb = $_GET['fname2'];
$namea = $_GET['fname'];
}
// $nameb = Dolce+Gabana ;
// $namea = Nike+Company;
?>
in above code php varibales equal to term name. But how can I get term id from term names. I use custom taxonomy
Solution
Try to use get_term_by()
, where first argument is a field, in your case - name. Second is your value. I used esc_attr()
to make it secure. Third one is taxonomy, as example I put here category
.
if ($_SERVER["REQUEST_METHOD"] == "GET" && $_GET['fname2'] && $_GET['fname']) {
$nameb = get_term_by('name', esc_attr($_GET['fname2']), 'category');
$namea = get_term_by('name', esc_attr($_GET['fname']), 'category');
}
//check if there is an objects
if( $nameb instanceof WP_Term && $nameb instanceof WP_Term ){
echo $nameb->term_id;
echo $namea->name;
}
Reference with some examples - here
Returned object:
(object) array(
'term_id' => 49,
'name' => 'Term Name',
'slug' => 'term-name',
'term_group' => 0,
'term_taxonomy_id' => 49,
'taxonomy' => 'category',
'description' => '',
'parent' => 0,
'count' => 286,
'filter' => 'raw',
)
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange