megclaypool
3/21/2019 - 7:24 PM

WordPress Custom PHP Functions for Preprocessing Fields Prior to Use in Twig Templates

[WordPress Custom PHP Functions for Preprocessing Fields Prior to Use in Twig Templates]

Probably should put these functions in functions.php so they're available to be called in php templates

/**
 * Converts the output of a WP ACF image field into a variable 
 * ready for our card srcset twig template 
 * 
 * I'm noticing now that Jason has done something very similar
 * but fancier just below... ¯\_(ツ)_/¯ 
 */
function acf_image_to_srcset($acf_image_field, $wp_image_size, $sizes = '100vw') {
  $temp['srcset'] = wp_get_attachment_image_srcset( $acf_image_field['id'], $wp_image_size );
  $temp['alt'] = $acf_image_field['alt'];
  $temp['src'] = $acf_image_field['url'];
  $temp['caption'] = $acf_image_field['caption'];
  $temp['sizes'] = $sizes;

  return $temp;
}

This one actually goes into RadicatiSite.php, since that's where the add_to_context function lives:

public function preprocess_wp_menu_for_twig($orig_menu) {
  for($i = 0; $i < count($orig_menu); $i++) {
    if( $orig_menu[$i]->children) {
      $this->preprocess_wp_menu_for_twig($orig_menu[$i]->children);
    }
    $orig_menu[$i]->title = $orig_menu[$i]->name;
    $orig_menu[$i]->link = $orig_menu[$i]->url;
  }
  return $orig_menu;
}