Support

Account

Home Forums General Issues Same image on category page and all its child pages with ACF Reply To: Same image on category page and all its child pages with ACF

  • 
    <?php 
    
    // added to single.php
    // if outside of "The Loop" we need to get the current post id
    $queried_object = get_queried_object();
    $post_id = $queried_object->ID;
    
    // gets a list of all post categories
    $categories = wp_get_post_categories($post_id);
    // you could also limit the list returned above by including
    // secong $args parameter for function, for more info see
    // https://developer.wordpress.org/reference/functions/wp_get_post_categories/
    
    $url = false; // initialize $url value
    
    if (count($categories)) {
      // the post has one or more categories
      // loop through them and see if any has an image set for the field
      foreach ($categories as $category) {
        $value = get_field('featuredimage', $taxonomy.'_'.$category->term_id);
        if ($value) {
          // this category has an image
          // you could also do more checking here
          // if there are other conditions to
          $url = $value;
          // in this case, use the first category that has an image
          // once we find an image stop looking
          break;
        } // end if $value
      } // end foreach categories
    } // end if categories
    ?>
    <div id="banner"<?php 
      if ($url) {
        ?> style="background-image: url(<?php echo $url; ?>);"<?php 
      } // end if url
      ?>>