Custom Post Type - single page, moving wp_get_post_terms into Controller / View setup

I have the following code to output a taxonomy term into a single view. It works, but I’d like to refactor it to work more efficently in the Sage way:

content-single-producer.blade.php

  @php
  global $post;
  $terms = wp_get_post_terms( $post->ID, 'region');
  foreach ( $terms as $term ) {
    $producer_region = $term->name;
  }
  @endphp

  @include('partials.page-title-group', [
    'subtitle' => $producer_region,
    'title' => get_the_title(),
    'text' => $producer_short_description,
  ])

The $producer_region is the taxonomy term (‘region’) connected to the custom post type that I need to pass through to the layout partial.

To improve this, I can move this over to a Controller / View setup like so:

SingleProducer.php

  public static function producerRegion()
  {
    global $post;
    $terms = wp_get_post_terms( $post->ID, 'region');

    foreach ( $terms as $term ) {
      echo $term->name;
    }
  }

content-single-producer.blade.php

  @include('partials.page-title-group', [
    'subtitle' => SingleProducer::producerRegion(),
    'title' => get_the_title(),
    'text' => $producer_short_description,
  ])

However, this quite work as the taxonomy term gets output outside the include structure (https://cl.ly/381f7a6166a0). Can anyone verify whether this is a valid approach or if it could be improved in the Sage way? Thanks

My solution to this was to return rather than echo:

foreach ( $terms as $term ) {
  return $term->name;
}

This topic was automatically closed after 42 days. New replies are no longer allowed.