Query Builder Components
WP-Node heavily relies on Knex.js for querying WordPress database. While Knex.js already provides many built-in helpers, WP-Node extends its functionality by offering specialized Query Builder components for each WordPress table, making it easier and more type-safe to work with.
Using QueryUtilβ
When WP-Node initializes a new Context, you gain access to QueryUtil component via context.utils.query. This utility provides access to a set of builders for common WordPress tables.
Example Usage:
const context = await Application.getContext();
const queryUtil = context.utils.query;
// Querying posts with post_type = "post", excluding post_status = "draft"
const posts = await queryUtil.posts((query) => {
query.where("post_type", "post").andWhereNot((query) => {
query.where("post_status", "draft");
});
// View the raw SQL query (for debugging)
console.log(query.builder.toString());
});
Each builder method accepts a callback that receives QueryBuilder instance, allowing you to construct complex queries fluently.
Available Buildersβ
context.utils.query object exposes the following query builder components, each corresponding to a WordPress database table:
commentsβwp_commentsmetaβwp_postmeta,wp_usermeta, etc.postsβwp_postssiteβ multisite table accesstermsβwp_terms,wp_term_taxonomy, etc.usersβwp_users
Each component provides custom helpers on top of Knex.js, tailored to its respective table schema.
π Tip: Explore
query-builderdirectory to learn more about available builder methods and utilities.
builder Propertyβ
Every builder instance exposes a .builder property that returns the underlying Knex.js query builder object. This gives you full access to Knexβs query methods, enabling things like:
const context = await Application.getContext();
const queryUtil = context.utils.query;
const posts = await queryUtil.posts((query) => {
query.where("post_status", "publish");
query.builder.limit(5).orderBy("post_date", "desc");
});
Summaryβ
- QueryUtil is the entry point for database access in WP-Node.
- Each builder maps to a WordPress table and provides fluent query construction.
- You can mix WP-Node helpers and raw Knex methods through the .builder accessor.
- All query components are available under
context.utils.query.