Skip to content

Better Post => array translation #2312

@acobster

Description

@acobster

Inspired by discussion on #2311 and #1434.

At times you may want to prepare certain Post data, such as when converting to JSON or switching between sites in a network:

switch_to_blog( $id );

$latest_posts = Timber::get_posts( [
	'orderby'        => 'post_date',
	'posts_per_page' => 0,
] );

// Prepare all the data you need in advance.
foreach ( $latest_posts as $latest_post ) {
	$news[] = [
		'link'    => $latest_post->link(),
		'title'   => $latest_post->title(),
		'content' => $latest_post->content(),
	];
}

restore_current_blog();

It would be a lot nicer if you didn't have to worry about fetching the data you want manually:

foreach ( $latest_posts as $latest_post ) {
  $news[] = $latest_post->to_array();
}

It would be even nicer if collections knew how to do this for you:

$latest_posts = Timber::get_posts( [
	'orderby'        => 'post_date',
	'posts_per_page' => 0,
] )->to_array_deep();

Acceptance Criteria:

  • implement the JsonSerializable interface on Post
  • implement Timber\Post::to_array()
  • implement ::to_array_deep() on PostQuery and PostArrayObject (perhaps using a trait?)
  • design semantics for returning nested relations from Post::to_array(), e.g. parent() (need a way to prevent infinite recursion - do we want a Timber\Post::to_array_deep()?)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions