0

I have list items. These are custom posts.

  • Post A belongs to category green and blue

  • Post B belongs to category blue

  • Post C belongs to category green and blue

  • Post D belongs to category green and red

  • Post E belongs to category green and blue

  • Post F belongs to category blue

  • Post G belongs to category blue and yellow

I want to loop each post and display second category name only of the post if there is one. If theres is not display the first category name as default.

So A should display category blue

B should be blue

C should be blue

D should be red

E should be blue

F should be blue

G should be yellow

Please help me achieve this using php. I beleive get_post _terms() is what needed here but I struggle to do it. Thanks in advance.

1

Inside of your loop you can get the terms via wp_get_post_terms function. Then, check if two or more terms exist. If they do, then use the function array_slice to extract the second term that appears in the array:

$term_list = wp_get_post_terms( $post->ID, 'YOUR_TAXONOMY', array('orderby' => 'name', 'order' => 'ASC', 'fields' => 'all') );

$display_term = (count($term_list) > 1) ? array_slice($array, 1, 1) : $term_list;

However, this does not determine how the terms will output from the database. You may want to define the orderby parameter to be something specific so you can predict which term will appear second.

Sources:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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