<?php
$context = Timber::get_context();
$post = new TimberPost();
$context['post'] = $post;
$context['entries'] = Timber::get_posts('post_type = post');
//var_dump( Timber::get_posts('post_type = post'));
$templates = array( 'page-' . $post->post_name . '.twig', 'page.twig' );
//if ( is_front_page() ) {
//    array_unshift( $templates, 'frontpage.twig' );
//}

// Areas de proyectos
$areas = get_terms( [
        'taxonomy' => 'category',
        'parent' => 29,
        'hide_empty' => false,
        ]
    );
$context['areas'] = $areas;

// Servicios
$serviciosterms = get_terms( [
        'taxonomy' => 'category',
        'parent' => 138,
        'hide_empty' => false,
        ]
    );
$context['serviciosterms'] = $serviciosterms;

// templatetag para filtrar los post con categorias de Servicios
function posts_by_service($numberposts=-1,$postslug,$slug,$template_name='posts_by_service.twig') {
    $args = [
        'numberposts' => $numberposts,
        'post_type' => 'post',
        'post_status' => 'publish',
        'orderby' => array(
        'date' => 'DESC'
		),
		'tax_query' => array(
			array(
				'taxonomy' => 'category',
				'field'    => 'slug',
				'terms'    => array($postslug, $slug),
				'operator' => 'AND',
			)
		),
    ];
    $context = Timber::get_context();
    $ctx = ['posts' => Timber::get_posts( $args ), 'areas' => $context['areas']];
    return Timber::fetch($template_name, $ctx);
}


add_filter( 'timber/twig', function( \Twig_Environment $twig ) {
    $twig->addFunction( new Timber\Twig_Function( 'posts_by_service', 'posts_by_service' ) );
    return $twig;
} );
// fin del templatetag

Timber::render( $templates, $context );
