Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save westonruter/30bff062cb24f7eb08eb089e701e07c5 to your computer and use it in GitHub Desktop.
Save westonruter/30bff062cb24f7eb08eb089e701e07c5 to your computer and use it in GitHub Desktop.
<?php
function nl_amp_set_schema_type( $metadata, $post ) {
if ($post->post_type == 'recipe') {
$metadata['@type'] = 'Recipe';
$metadata['name'] = $post->post_title;
$metadata["recipeYield"] = get_field('new_serves', $post->ID);
$metadata['description'] = get_field('description', $post->ID);
// Prep Time
if (get_field('prep_time_hours') OR get_field('prep_time_minutes')) {
$prep_duration = 'PT';
if (get_field('prep_time_hours')) {
$prep_duration .= get_field('prep_time_hours') . 'H';
}
if (get_field('prep_time_minutes')) {
$prep_duration .= get_field('prep_time_minutes') . 'M';
}
$metadata['prepTime'] = $prep_duration;
}
// Cook Time
if (get_field('cook_time_hours') OR get_field('cook_time_minutes')) {
$cook_duration = 'PT';
if (get_field('cook_time_hours')) {
$cook_duration .= get_field('cook_time_hours') . 'H';
}
if (get_field('cook_time_minutes')) {
$cook_duration .= get_field('cook_time_minutes') . 'M';
}
$metadata['cookTime'] = $cook_duration;
}
// Get Total Time
$total_duration = false;
if ($prep_duration OR $cook_duration) {
$e = new DateTime('00:00');
$f = clone $e;
if ($prep_duration) {
$p = new DateInterval($prep_duration);
$e->add($p);
}
if ($cook_duration) {
$c = new DateInterval($cook_duration);
$e->add($c);
}
$metadata['totalTime'] = $f->diff($e)->format("PT%hH%iM");
}
elseif (get_field('new_time')) {
$i = DateInterval::createFromDateString(get_field('new_time'));
$metadata['totalTime'] = $i->format("PT%hH%iM");
}
if ($recipe_category = get_yoast_primary_category('recipe_categories')) {
$metadata['recipeCategory'] = $recipe_category;
}
if ($calories = get_field('calories')) {
$metadata['nutrition']['@type'] = 'NutritionInformation';
$metadata['nutrition']['calories'] = $calories . ' calories';
}
while (have_rows('new_ingredients', $post->ID)) { the_row();
$metadata['recipeIngredient'][] = get_sub_field('quantity') . ' ' . get_sub_field('ingredient');
}
$instructions = '';
$i = 1;
while (have_rows('directions', $post->ID)) { the_row();
$instructions .= $i++ . '. ' . get_sub_field('step') . '\n';
}
$metadata['recipeInstructions'] = $instructions;
// $metadata['aggregateRating'] = array(
// '@type' => 'AggregateRating',
// 'ratingValue' => the_ratings($post->ID)
// );
}
return $metadata;
}
add_filter( 'amp_post_template_metadata', 'nl_amp_set_schema_type', 10, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment