The Site Object
site() function in any of your theme’s php files will return the
ofc/Site object, a class with a collection of convenient methods to interface with various parts of WordPress.
Developers familiar with the WordPress' WP_Query concept of querying for posts will feel right at home with better-wordpress.
If you want to quickly fetch 8 posts of type “product”, for example:
$products = site()->getPosts([ "post_type" => "product", "numberposts" => 8 ]);
But unlike a normal WP_Query, better-wordpress' comes with an additional option to make working with taxonomies easier. Now if I want to grab products that have the “medium” taxonomy equal to the term with slug “vinyl”, I would simply use:
$records = site()->getPosts([ "post_type" => "product", "taxonomy.medium" => "vinyl" "numberposts" => 8, ]);
Additionally a number of aliases for commonly used fields are added by better-wordpress, which are defined in the
One convenient feature of better-wordpress is the ability to define the structure of a returned post object on certain methods.
In practice this simply means creating a string array of
WP_Post members you want returned. For example, if I only want to get the
$post_author of a post, my fields would look like this:
$fields = ['post_title','post_author']; // Get these fields from post with id 4 $post = site()->getPost(4,$fields);
The result of getPost is the following:
[ "post_title" => "My Blog Post", "post_author" => "Escher" ]
Check out this
getPost example to see some of these fields in action.
id– Shortcut to return the
title– Shortcut to return the
name– Shortcut to return the
get_permalink($id)to fetch the url of the post.
permalink– Same as
get_the_post_thumbnail_url($id)to get the post thumbnail.
content– Retrieves the content of the post.
excerpt– Retrieves the post excerpt, if enabled.
meta.<key>– Get the value of a specific post meta field.
acf.<key>– Get the value of a specific ACF field for this post.
categories.<member1>,<member2>,...– Get specific members of the
WP_Termfor each category this post is a part of.
taxonomy.<taxonomy>.<member1>,<member2>,...– Get specific members of the
WP_Termfor each term within the given taxonomy this post is a part of. See below for members:
id– Alias for
link– The result of
title– Alias for
Putting it Together
Now that we know how to create a post query and define it’s structure, the logical next step would be to put them together! Luckily with better-wordpress this is super simple, just use the
getPosts function with both parameters.
If I want to grab the title, url, and thumbnail for all the records I’m selling, for example:
$query = [ "post_type" => "product", "taxonomy.medium" => "vinyl" ]; $fields = [ "title", "url", "thumbnail" ]; $records = site()->getPosts($query,$fields);
Check out the
getPosts docs for more information.