Support

Account

Home Forums Front-end Issues Custom Field Not Displaying in Front End Reply To: Custom Field Not Displaying in Front End

  • 
    <?php 
      $taxonomy = 'product_cat';
      $queried_object = get_queried_object(); 
      $post_id = $queried_object->ID;
      $terms = wp_get_post_terms($post_id, $taxonomy, array('fields' => 'ids'));
      $term = false;
      
      // find a term that is at the top level this will fail 
      // if no top level terms are assigned to the post
      if (count($terms)) {
        foreach ($terms as $term) {
          if (!$term->parent) {
            // parent is 0 = top level term
            break;
          }
        }
      }
      // the above loop will exit with term = a top level term 
      // or the last term or false if there are no terms 
      // assigned ot the post
      
      // the next section will get the top level term
      // of the first term assigned to this post
      // if the term from the above loop is not
      // a top level term
      if (count($terms) && $term->parent) {
        // parent is not 0 and there are terms
        $term = $terms[0];
        $parent = $term->parent;
        while ($parent != 0) {
          $term = get_term_by('id', $parent, $taxonomy);
          $parent = $term->parent;
        } // end while $parent == 0
      }
      // this section will exit with either
      // a top level term or false
      
      // test for term == false before using it
      if ($term) {
        $image = get_field('products_background_image', $taxonomy . '_' . $term_id);
      }
    ?>
    <div class="catback"<?php 
        if ($image) {
          ?> style="background-image: url('<?php echo $image; ?>');"<?php 
        }
      ?>></div>