Skip to main content

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_comments
  • meta β†’ wp_postmeta, wp_usermeta, etc.
  • posts β†’ wp_posts
  • site β†’ multisite table access
  • terms β†’ 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-builder directory 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.