PostUtil
PostUtil is a helper utility for working with WordPress posts, including fetching, visibility checks, metadata access, and slug generation.
Description
- Converts raw DB records into
Post
instances. - Resolves visibility of posts by status/type.
- Provides helpers to fetch attachments and metadata.
- Generates unique post slugs and retrieves post type/status objects.
- Wraps logic from core WordPress behaviors (e.g.
get_post_status
,get_attached_file
).
Usage
const context = await Application.getContext();
const post = await context.utils.post.get(postId);
const postBySlug = await pcontext.utils.post.getBySlug("hello-world");
const isPublic = await context.utils.post.isPubliclyViewable(post);
Methods
toPost
toPost(post: types.Tables["posts"]): Post
Converts a raw post object to a Post
instance.
toPosts
toPosts(posts: types.Tables["posts"][]): Post[
Maps multiple raw post records into Post
instances.
get
get(id: number): Promise<Post>
Fetches a Post
instance by ID.
getBySlug
getBySlug(slug: string): Promise<Post | undefined>
Finds a post by post_name
(slug) and returns a Post
instance.
isPubliclyViewable
isPubliclyViewable(postIdOrPost: number | Post): Promise<boolean>
Determines if a post is visible to the public.
getViewableTypes
getViewableTypes(): types.PostType[]
Returns a list of publicly viewable post types based on config.
isTypeViewable
isTypeViewable(type: string | PostTypeObject): boolean
Returns true
if a post type is public and queryable.
isStatusViewable
isStatusViewable(status: string | PostStatusObject): boolean
Returns true
if a post status is publicly visible.
getStatusObject
getStatusObject(status: string): PostStatusObject | undefined
Returns a status config object for a given status name.
getStatus
getStatus(post?: Post, parent?: Post): Promise<string | undefined>
Resolves the true status of a post, especially for attachments.
getAttachedFile
getAttachedFile(postId: number, unfiltered?: boolean): Promise<string | undefined>
Returns the full file path for a post attachment.
getAttachmentMetadata
getAttachmentMetadata<T = Record<string, any>>(postId: number): Promise<T | undefined>
Fetches and parses _wp_attachment_metadata
.
getTypeObject
getTypeObject(name: string): PostTypeObject | undefined
Returns a post type configuration from the global config.
getUniqueSlug
getUniqueSlug(
slug: string,
post: number | Post,
maxSuffix?: number
): Promise<string>
Generates a unique slug by checking for conflicts, appending suffixes if needed.