Support

Account

Home Forums General Issues How to filter tax terms by custom field, what am I doing wrong here?

Solved

How to filter tax terms by custom field, what am I doing wrong here?

  • I am trying to list all terms from the custom taxonomy: “book_type” that have the name ‘fiction’ in the taxonomy custom field ‘book_group’

    I use this code, but it won’t work: (code based on this topic: http://wpquestions.com/question/showChrono/id/9779 )

    <?php 
    
    	$terms = get_terms( 'book_type', array(
        	'hide_empty' => 0
    		) );
    
    			
    	foreach( $terms as $term ) {     
    	
    	if( get_field('book_group', 'book_type_'.$term->term_id) != 'fiction:Fiction' ) 
    
    			continue;
    	
    	 echo '<div>' . $term->name . '</div>';
    
    				
      	} 
    ?>

    Is the get_field used right here? With the term Id instead of the post_id. In the topic I found this example code, they say it works. Any suggestions what I am doing wrong here?

    I tried with ‘fiction’ instead of ‘fiction:Fiction’ too.

  • What type of field is “book_group”

  • Hi Hube2

    The Field Type is: Checkbox

  • checkobxes are stored as serialzed data. The value returned by get_field is going to be an array. So you need to do something like:

    if (in_array('Fiction', get_field('book_group', 'book_type_'.$term->term_id))

  • Thank you, now I have this code, but some syntax error occurs on the line with the if statement:

    <?php 
    	$terms = get_terms( 'book_type', array(
        	'hide_empty' => 0
    		) );
    
    			
    	foreach( $terms as $term ) {     
    	
    	if (in_array('Fiction', get_field('book_group', 'book_type_'.$term->term_id))	 
     {
    
    			continue;
    	
    	 echo '<div>' . $term->name . '</div>';
    
    	}
      	} 
    ?>
  • I missed a closing parenthesis on my if statement

    
    <?php
    //start by fetching the terms for the product_type taxonomy
    $terms = get_terms( ‘product_type’, array(
    ‘hide_empty’ => 1
    ) );
    
    foreach( $terms as $term ) {
    
    if (in_array(‘Fiction’, get_field(‘book_group’, ‘book_type_’.$term->term_id))) {
    
    continue;
    
    echo ‘<div>’ . $term->name . ‘</div>';
    
    }
    }
    ?>
    
  • Thanks Hube2!

    I needed to remove the continue; to get it to work.

Viewing 7 posts - 1 through 7 (of 7 total)

The topic ‘How to filter tax terms by custom field, what am I doing wrong here?’ is closed to new replies.