Okay, so a couple days ago I re-built my headless site in WordPress, and in doing so ran into a stumbling block – I couldn’t figure out how to make my feed show different templates based on the post format. I did some digging, and eventually found my way to a pull request that is starting to give some progress toward supporting post formats, but it’s still a long ways away from doing what I’m hoping it will do, considering the request only accounts for querying.
Meanwhile, you have plugins that extend WordPress that tend to move faster than WordPress core. For example the advanced query loop has long-since solved this (and so much more). And…maybe that’s okay? That’s kinda the beauty of WordPress, right?
I’ve been expressing my frustration, and also reaching out to some people online.
Then, Tom Finley and Mike McAlister both jumped into that thread and gave me some ideas, including and one particularly great suggestion – to use another block plugin called block visibility, which makes it possible to conditionally disable certain blocks in your content.
This plugin has some really awesome capabilities, and definitely can solve my problem – all I need to do is set up the query loop with a post template that has two group blocks – one for “aside” post formats, and the other for “standard” post formats.
There’s just one problem – The block visibility plugin doesn’t natively support post formats 😭. Luckily, it does support post meta, however, since it supports post meta, I can filter the post meta field to use post formats to set a meta value dynamically. It’s a little bit of a hack, but it absolutely solves my problem!
Here’s the snippet that I’m using to convert post formats as a post meta, fresh from pluginception, if you’re interested.
<?php
/*
Plugin Name: Post Format As Post Meta
Description: Adds a hook that makes it possible to access the current post
*/
add_filter('get_post_metadata', function ($value, $post_id, $meta_key, $single) {
if ('_as_post_format' === $meta_key) {
// Get the post format for the post
$post_format = get_post_format($post_id);
if ($post_format) {
return $post_format;
} else {
return 'standard';
}
}
return $value;
}, 10, 4);
With that snippet in-place, I can add conditionals to my site to display blocks based on the post format. boom baby!
HUGE thanks to Tom and Mike for the nudge in the right direction. This was a big time saver for me!
Leave a Reply