0

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

1 Answer 1

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',
)
3
  • i willl complete this like this ? $aa = $namea->id; $bb = $nameb->id; Commented May 1, 2021 at 17:11
  • I updated an answer. Check first if there is not false if( $nameb ) or if its a term object like I did. I put also available properties of term object.
    – anton
    Commented May 1, 2021 at 17:26
  • Thank you very much brother . everything works now Commented May 1, 2021 at 17:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.