1

I'm just learning PHP, and I'm using get_terms to get some text descriptions from the CMS, but i want to assign 3 variables to only 3 of my woocommerce tags. My code works well, but I just want to learn if there's a better way to filter by $tag_descrip->name than using if conditions.

This is my code:

<?php
$tag_descrip = get_terms( 'product_tag', 'orderby=count&hide_empty=0' );
$count = count($tag_descrip);


if ( $count > 0 ){

 foreach ( $tag_descrip as $tag_descrip ) {

 if($tag_descrip->name == "parfum_bestof")
   {$title_new1 = $tag_descrip->description ;}

 if($tag_descrip->name == "tshirt_bestof")
   {$title_new2 = $tag_descrip->description ;}

 if($tag_descrip->name == "child_bestof")
   {$title_new3 = $tag_descrip->description ;}



 }



}

?> 

Thanks

2
  • Generic PHP questions are off-topic here. You could try asking this on Stack Overflow. Commented Dec 3, 2012 at 15:25
  • 1
    It isn't necessarily off-topic... I think the OP is asking how to query 3, specific tags? But I can't really tell because I don't know the use case for the above code. Commented Dec 3, 2012 at 15:27

1 Answer 1

1

Hi there is not better option, but to speed it up little you can use wordpress transient, see documentation: http://codex.wordpress.org/Transients_API

your code would look like this (and i cleaned it bit and used function empty to check array...):

<?php

if ( false === ( $tag_descrip = get_transient( 'tag_descrip' ) ) ) {

     $tag_descrip = get_terms( 'product_tag', 'orderby=count&hide_empty=0' );

     set_transient( 'tag_descrip ', $tag_descrip );
}


if ( !empty($tag_descrip) ){

 foreach ( $tag_descrip as $tag_descrip ) {

 if($tag_descrip->name == "parfum_bestof")
   $title_new1 = $tag_descrip->description;

 if($tag_descrip->name == "tshirt_bestof")
   $title_new2 = $tag_descrip->description;

 if($tag_descrip->name == "child_bestof")
   $title_new3 = $tag_descrip->description;

}


}

?> 
3
  • foreach ( $tag_descrip as $tag_descrip ) – there is some room for improvement in the variable names … ;)
    – fuxia
    Commented Dec 3, 2012 at 15:48
  • Thanks ! Seems like a good idea, I'm going to try it too but what's meaning of the operator "===" in PHP code, why we use "===" instead of "==" ? Commented Dec 3, 2012 at 19:21
  • Whereas the "===" operator is type strict, "==" will attempt to cast the operands. See documentation.
    – ScheRas
    Commented Oct 7, 2016 at 7:25

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.