Post Types

Introduction

Typically in WordPress when you're querying posts you get WP_Post objects back. Timber have taken this a step further and return a Timber/Post object instead. This has a ton of great helper methods and properties which makes it easier and more expressive to use.

use Timber\Post;

$post = new Post(1);
$posts = Timber::get_posts($wpQueryArray);

Lumberjack has its own Post object which makes it easier and more expressive to run queries.

use Rareloop\Lumberjack\Post;

$post = new Post(1);
$collection = Post::query($wpQueryArray);

This becomes especially powerful when you start registering Custom Post Types.

use App\PostTypes\Product;

$post = new Product(1);
$collection = Product::query($wpQueryArray);

In this example $collection contains App\PostType\Product objects. That allows you to add your own methods to a product and encapsulate logic in one place.

use App\PostTypes\Product;

$collection = Product::query($wpQueryArray);

foreach ($collection as $product) {
    echo $product->price();
}

If collections are new to you, be sure the check out the documentation on them:

Collections

Register Custom Post Types

First, create a new file in app/PostTypes/. We recommend using singular names. For this example, lets add a Product.php file there.

You can use this boilerplate to get you started:

Lumberjack will handle the registering of the post type for you. In order to do that, it requires 2 methods (documented above):

  • getPostType()

  • getPostTypeConfig()

In order for Lumberjack to register your post type, you need to add the class name to the config/posttypes.php config file.

And that's it! You can now start using your new Custom Post Type.

Tip: Try and avoid using ACF's get_field outside of a Post Type class where possible. This will help make your application easy to change.

Available Methods for Rareloop\Lumberjack\Post

Lumberjack's Post class extends Timber\Post, and adds some convenient methods for you:

Extending Post Types

The Lumberjack Post class can be extended with custom functionality at runtime (the class is "macroable"). The following example adds an acf method to the Post class that can be used to access Advanced Custom Field (ACF) field values:

Last updated