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
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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', )
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0