Post
Post
class is a transient component that wraps a WordPress wp_posts
row and provides structured methods for working with post relationships, metadata, authors, and taxonomies.
Description
- Data Wrapper – Encapsulates
wp_posts
row data and allows lazy loading of related entities. - Scoped Context – Uses
Meta
to mark the current post context. - Transient Lifecycle – A new instance is created per request (via
@component
withTransient
scope). - Async Init – Automatically populates post data via the
@asyncInit
decorator if a validpostId
is provided. - Flexible Access – Offers
filter
modes andwithProps()
for runtime data shaping.
Properties
-
filter: "raw" | "edit" | "db" | "display" | "sample"
Optional filter mode (default:"raw"
). Can be used to shape the format or intent of post data access. -
props: Props | undefined
Getter for the post's raw properties. May be undefined until async initialization is complete.
Methods
withProps(props: Partial<Props>): this
Merge additional fields into the current _props
.
async children(): Promise<Props[]>
Returns the post's children using a withChildren()
query.
Caches the result on first call.
async parents(): Promise<Props[]>
Returns the post’s parent lineage (ancestors) using a withParents()
query.
Caches the result once loaded.
async terms(taxonomy: TaxonomyName): Promise<WpTerms[]>
Retrieves terms for the given taxonomy.
- Caches results in
_terms
map. - Logs a message if terms aren't found.
async author(): Promise<WpUsers | undefined>
Returns the post’s author as a user object.
Uses post_author
field and queries via QueryUtil
.
private async init(): Promise<void>
Called automatically if postId > 0
via @asyncInit
.
Loads post data from the database and sets it to _props
.
Logs if the post isn't found.
Usage
const context = await Application.getContext();
const post = await context.container.get(Post);
const author = await post.author();
const children = await post.children();
const tags = await post.terms("post_tag");