Workaround for querying non-serialized metadata in Wordpress

Workaround for querying non-serialized metadata in Wordpress

This articles shows how to filter query output on values used in a Wordpress meta-box. By default it contains not serialized data which makes it harder to filter but with a little workaround it can work.

Data structure post (excerpt, output from a php var_dump)

  string(1) "1"
  string(0) ""
  string(19) "2019-06-18 23:02:32"
  string(214) "..."
  ... more fields here ...
  array(5) {
    string(1) "1"
    string(10) "18-06-2019"
    string(19) "ECLI:NL:HR:2019:572"
    string(71) ""
    string(0) ""
  string(3) "120"

The metabox is named vscc_zaak_metadata and where we are interested in is show_in_widget. For our purpose we want this value not to be 0. Simply put, we only want when the value equals 1 or doesn't exist.

How it is stored in MySQL

In the database there is a table named wp_postmeta that contains the metadata fitted to wp_posts table records. In our sample exists (or not) a metadata record with a metakey vscc_zaak_metadata that contains the following (not serialized) value.


How to query this?

The meta query we would like to execute. I have split this to have a better view for this article, but you can merge it with the *select in the next PHP sample code.

$metaQuery = [
        'key' => 'vscc_zaak_metadata',
        'compare' => 'not like',
        'value'   => '"show_in_widget";s:1:"0"'

And the select itself:

$args = [
  'more' => 'args that come with the function',
  'showposts' => 20

$queryArgs = array_merge([
    'post_type'   => 'vscc-zaak', // <-- custom post
    'post_status' => 'publish',
    'orderby'     => 'date',
    'order'       => 'desc',
    'meta_query'  => $metaQuery // <--- notice this !!!
], $args);

$posts = get_posts($queryArgs);

More from same category