0

i've a problem showin a list categories.

    $args = array(
      'orderby' => 'name',
      'order' => 'ASC'
    );
    $categories = get_categories($args);
        foreach($categories as $category) { 
          echo '<a class="cover margin-ultimos" href="' . get_category_link( $category->term_id ) . '"><div id="cover-home" class="gray-shadow"><img src="'.(( $terms = get_the_category() ))? the_field( 'portada', 'category_'.$terms[0]->term_id ):'" alt="Portada'. get_the_title ( $ID ) . '" /></div></a>';
            } 

The code to show the fiel is that:

if ( $terms = get_the_category() ) the_field( 'portada', 'category_' . $terms[0]->term_id );

Maybe i must to use a ternary operator to put if stament in echo. But i can. Can help me please? Thanks!

0

What do you try to achieve exactly ? Do you want to list categories that have an image custom field ?

If yes, try this :

 <?php
    $args = array(
      'orderby' => 'name',
      'order' => 'ASC'
    );
    $categories = get_categories($args);

    foreach($categories as $category) { 

        // check if image field is set on category
        if ( get_field( 'portada', 'category_' . $category->term_id ) ) {
            // display link
            echo '<a class="cover margin-ultimos" href="' . get_category_link( $category->term_id ) . '"><div id="cover-home" class="gray-shadow"><img src="'. get_field( 'portada', 'category_'.$category->term_id ). '" alt="Portada'. get_cat_name ( $category->term_id ) . '" /></div></a>';
        }

    } 

A few mistakes in your code :

  • you should test if the image exists before displaying the link
  • use get_field instead of the_field inside an echo
  • you don't need to get request a new category object because you are already looping them
  • use get_cat_name instead of get_the_title when retrieving category title
| improve this answer | |

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.