Accessing the current post

The WordPress template hierarchy defines a number of templates that can be used to display single objects from your WordPress site:

  • single.php – a single standard post, attachment, or post based on a custom post type
  • single-post_type.php – a post based on a custom post type
  • page.php – a single page

In a standard WordPress theme, the current post or page is usually displayed by embedding template tags for the post inside The Loop, with the assumption that The Loop will only return one post in this scenario:

Example 1: Simplified example of The Loop for a single template

In Integrating with The Loop, and the WOOF loop we discuss how the method WOOF::the is used to access the current post inside an archive loop, so our code to access the single post could be rewritten to use the MasterPress API, like so:

Example 2: Accessing the current post using the MasterPress API

It’s also worth noting here that we could actually drop the boilerplate Loop code altogether in this example, and it would still work correctly. The downside to this is that some plug-ins and standard template tags may not work correctly without it, so you need to be careful – if you use MasterPress API code exclusively, you certainly can remove it though.

The current post type

In single and archive templates, we also have the notion of an active post type. WOOF provides easy access to this object via the WOOF::the_type method:

Example 3: Accessing the current post type

It’s important to note that this returns a WOOF_PostType object, and not just the name of the post type. You can access the post type name via the name property as shown in this example.

For ultimate brevity, the WOOF::type method, which can be used to retrieve a specific post type object, will return the current post type if no arguments are provided:

Example 4: Another way to access the current post type

The current page

Since a page in WordPress is simply a post with the post type page, we access the current page in the same way as the current post, with WOOF::the.

Latest From the Blog

MasterPress 1.4.1 is now available

27th May 2024

This update addresses backwards compatibility issues that were introduced in the previous update. There were some edge cases where PHP 7 had issues and it didn’t work at all on PHP 5.6. We have now changed it so that the PHP 8 compatibility changes will now only affect PHP 8 and will be more thorough… 

Plugin Requirements

MasterPress requires a minimum of WordPress version 4.9, MySQL 5.6, and PHP version 5.6.20.

We also recommend that PHP is configured to use a memory limit of 64MB per request (128MB may be required for sites with higher complexity).

This plug-in is not compatible with the hosted service.

Three AM