Querying WordPress serialized ACF meta data using WP_Query

in #utopian-io6 years ago


Source: Pixabay.com

The Problem

Advanced Custom Fields (ACF) is a very popular WordPress plugin. I've used it in almost every theme I developed. Recently in a project a requirement was to show one post from a collection of posts based on day and month the post author specified in the Post Editor. A post can be shown on multiple day and month combinations. So, to create the day and month field in the Post Editor I thought multiselect dropdown ACF field would be a good choice.

On the front-end I have to show the post based on current day and month, and also make two dropdown available for users to select DAY and MONTH to view prespecified post for that day and month combination. So, to get the specific post for the day and month combination I have to iterate through posts and search for post that has the month and day combination. But the problem is ACF saves multiselect dropdown or multiselect checkbox inputs as serialized array into wp_postmeta table in the database. MySQL recognize serialized data as string so, I haven't found any way out to check for them.

Also I needed to get the post using Ajax requests, so I needed to use API and WP API doesn't include ACF data or any meta data available through public API endpoints. I could use a plugin to solve the issue, but just for one post type I was not comfortable using a plugin for added overhead.

This is how it looks on the WordPress Editor.

The Solution

After trying many things including exposing custom field data to regular API using register_rest_field but I could not settle on as it affected all the posts. I also wanted more control, so I was on my way to create a custom API route and serve data with custom callback function.

Custom API Endpoint

I created custom REST API route using the rest_api_init action and queried database using meta_query using WP_Query. As mentioned earlier MySQL treats serialized data as string, so I converted query strings as string and use LIKE to find if there any similarity between query string and serialized data on the database. I worked as expect.

You can find the source code on GitHub. I also provided the jQuery to load the post in the front-end from API. I hope it helps. 

Sort:  

Release the Kraken! You got a 1.91% upvote from @seakraken courtesy of @reazuliqbal!

You got a 0.75% upvote from @mercurybot courtesy of @reazuliqbal!

This post has received a 0.14 % upvote from @drotto thanks to: @reazuliqbal.

Your Post Has Been Featured on @Resteemable!
Feature any Steemit post using resteemit.com!
How It Works:
1. Take Any Steemit URL
2. Erase https://
3. Type re
Get Featured Instantly � Featured Posts are voted every 2.4hrs
Join the Curation Team Here | Vote Resteemable for Witness

This post has received a 0.49 % upvote from @morwhale thanks to: @reazuliqbal.

Coin Marketplace

STEEM 0.18
TRX 0.13
JST 0.029
BTC 57912.75
ETH 3070.69
USDT 1.00
SBD 2.33