Community

Can taxonomy_get_term_by_name be used in a PHP eval()?

I am in a situation where I have a view that needs to get its contextual filter from a segment of the url converted to a taxonomy term. There are a few cases where the url segment does not translate directly to the term, so I need to interject to modify the term id in those cases. I am trying to do this by using the contextual filter "Content: Has taxonomy term ID" with the option "Provide default value" and type "PHP Code". I have the validation criteria ready to receive a term id and if I put, for example:

<?php
return 49;
?>

for the PHP eval'd value, the view works as expected (where 49 is a valid TID). However, when I try this code:

<?php
$uri
= explode('/', request_uri());
$tag = $uri[2];
$term = taxonomy_get_term_by_name($tag);
return
$term->tid;
?>

I get the following error when I try to load the view:

Notice: Trying to get property of non-object in eval() (line 4...

I am 100% sure that the page I am loading has a valid tag name (in this case, the url content translates directly to the taxonomy term) and have found that even doing this:

<?php
$term
= taxonomy_get_term_by_name('valid_tag_name_here');
return
$term->tid;
?>

yields the same sort of error - that $term is a non-object.

Anyone have thoughts on why this isn't working? Or ideas for another way to approach it?

Thanks!
Chris

Comments

-

Hi,

taxonomy_get_term_by_name() apparently returns an array of term objects (see http://api.drupal.org/api/drupal/modules!taxonomy!taxonomy.module/function/taxonomy_get_term_by_name/7 ), not a single term object. You probably want something like

<?php
$term
= taxonomy_get_term_by_name('valid_tag_name_here');
return
$term[0]->tid;
?>
or
<?php
$term
= taxonomy_get_term_by_name('valid_tag_name_here')[0];
return
$term->tid;
?>

-

D'oh. I hate that I missed that, hah. Thanks for the help, all good now (:

nobody click here