<?php

function resource_grid_request ($request) {

	$taxonomy = $request->get_param('taxonomy');
	if (!isset($taxonomy)) $taxonomy = false;

	$term = $request->get_param('term');
	if (!isset($term)) $term = false;

	$offset = $request->get_param('offset');
	if (!isset($offset)) $offset = 0;

	$limit = $request->get_param('limit');
	if (!isset($limit)) $limit = 12;

	return resource_grid($taxonomy, $term, $offset, $limit);
}

// this query is run for the templates and the request more endpoint
function resource_grid ($taxonomy, $term, $offset, $limit) {
	
	if (!is_array($term)) $term = array($term);

	$args = array(
		'post_type' => 'free-resource',
		'posts_per_page' => $limit,
		'paged' => 1 + ceil(intval($offset) / intval($limit)),
	);
	if ($taxonomy && !empty($term)) {
		$args['tax_query'] = array(
			array(
				'taxonomy' => $taxonomy,
				'field'    => 'name',
				'terms'    => $term,
			)
		);
	}

	$data = new stdClass();
	$data->posts = array();

	$results = new WP_Query($args);

	while ($results->have_posts()) {
		$results->the_post();

		$data->posts[] = $post = new stdClass();

		$post->title = get_the_title();
		$post->link = get_permalink();
		$post->excerpt = get_the_excerpt();


		if ($image = wp_get_attachment_image_src(get_post_thumbnail_id(), "thumbnail")) {
			$post->image = $image[0];
		}
	}
	return $data;
}
