WordPress Post Formats in Corcel

Corcel is a Laravel package that greatly simplifies pulling data from a WordPress database. Using it’s so easy, in fact, it feels a bit like—and at the same time completely different from—using WP_Query.

Posts With a Certain Format

One thing I—a rather inexperienced Laravel user—struggled a bit with, though, is fetching posts by Post Format. No, scratch that. Fetching posts by Post Format is extremely easy (and illustrated in the docs not under Post Format but Taxonomies):

$posts = Post::taxonomy('post_format', 'post-format-status')->all();

Bam, all ‘status’ posts!

Posts With No Format at All

Anyhoo, what I really had a hard time figuring out was how to get all posts with no Post Format at all—i.e., in WordPress, ‘standard’ posts. There’s no ready-made method to do so, you see, and this does not work:

$posts = Post::whereHas('taxonomies', function ($query) {
  return $query->where('taxonomy', '<>', 'post_format');
})
->all();

Because each post always contains at least one category, i.e., a taxonomy but no Post Format, every single post is returned—including those, like ‘statuses’, with a Post Format! Not what I’m looking for.

This, however, does work (and it ain’t even hard to see why):

$posts = Post::whereDoesntHave('taxonomies', function ($query) {
  return $query->whereIn('taxonomy', ['post_format']);
})
->all();

Now, if a post comes with one or more taxonomies of which at least one’s a Post Format, it will not be returned. Bingo!

Mentions

  1. WordPress Digest (@DigestWordpress) on

    … reposted this!

    Via twitter.com, in reply to WordPress Post Formats in Corcel.

  2. PHP Synopsis (@php_synopsis) on

    … reposted this!

    Via twitter.com, in reply to WordPress Post Formats in Corcel.