Myzwer / foothillschurch

Bootcamp II is a wordpress theme (as well as an inside joke) designed to suit the needs of foothillschurch.com. It makes use of webpack, Babel, Sass, Tailwind, Browsersync, PostCSS, ESLint, Stylelint, Prettier and more. It is meant for that site, but if you can use it by all means go for it.
1 stars 1 forks source link

Don't declare functions in the template #63

Closed rain2o closed 2 weeks ago

rain2o commented 1 month ago

https://github.com/Myzwer/foothillschurch/blob/effc5bbf81497ae99f0561ab7849412fe9272bfd/single-message.php#L29-L49

Declaring a function inside of a template isn't great. Every time this template renders that function gets re-defined. In WP, typically something like this would go in functions.php. But since you've split yours up, this would be a prime example of a util.

I've seen this pattern in a few places, defining a function in a template. This suggestion applies to all of those locations. Here are the other locations I've found:

I'm noticing they all have the same name, but they all render different HTML. Probably will need a more clarifying name per function if you move them to utils. Like display_transcript_taxonomy_terms etc...


However, you could also make these template partials instead of functions, if you wanted to. Either one works.

For example, if you made components/taxonomies/message-terms.php like this

<?php
// Get the terms associated with the current post for the specified taxonomy
$terms = get_the_terms(get_the_ID(), $args['taxonomy_name']);
// Check if there are terms and ensure no WP_Error occurred
if ($terms && !is_wp_error($terms)) {
  // Initialize an array to store the term names
  $term_names = [];
  // Loop through each term
  foreach ($terms as $term) {
    // Add the term name to the array
    $term_names[] = esc_html($term->name);
  } ?>

  <p class="capitalize text-lg">
    <span class="font-bold"><?php echo esc_html($args['label']); ?>:</span> <?php implode(', ', $term_names); ?>
  </p>
<?php } ?>

Then in your template, you could call

get_template_part('components/taxonomies/message-terms', null, ['taxonomy_name' => 'topic', 'label' => 'Topics']);

The end result is the same thing. The main difference is this lets you write out the HTML like HTML rather than in a string, which I find easier to write and read. But ultimately, I'd say this decision is personal preference.