Skip to content

Instantly share code, notes, and snippets.

@mishterk
Last active August 19, 2021 05:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mishterk/58519502ef78a618c27e485d151cb36c to your computer and use it in GitHub Desktop.
Save mishterk/58519502ef78a618c27e485d151cb36c to your computer and use it in GitHub Desktop.

Controlling JSON encoded flags in ACF Custom Database Tables version 1.0.x

The ACF Custom Database Tables plugin uses JSON encoding to prepare complex values for storing in the database. This differs to WordPress' core approach as WordPress relies on serialization instead. By default, the plugin opts to not escape slashes when encoding but there may be times where additional flags need to be used. e.g; JSON_UNESCAPED_UNICODE.

The following example demonstrates how to short-circuit the plugin's encoding algorithm in order to define custom args for the wp_json_encode() function. It uses the acfcdt/filter_value_before_encode filter found in \ACFCustomDatabaseTables\Intercept\ACFInterceptBase::maybe_encode().

This example is JSON only

Note that this example is using JSON encoding which is what the plugin expects when attempting to decode data for return from the database.

Whilst it would be possible to use this same filter for an alternate encoding method (such as serialization) it would also then be necessary to correctly decode values using the acfcdt/filter_value_before_decode filter found in \ACFCustomDatabaseTables\Intercept\ACFInterceptBase::maybe_decode() as the plugin will, by default, attempt to decode JSON strings.

Version 1.1 and above

In future versions of the plugin, this filter will continue to work but there are additional filters that will be more appropriate for controlling the args passed to the wp_json_encode() function.

Where to place this code?

This should work fine in your theme's functions.php file. That said, anything related to database configuration would be better suited in a plugin as it is the type of configuration that is unlikely to change. Personally, I prefer to put my ACF Custom Database Tables config in an MU plugin to prevent anyone from deactivating it but a standard plugin will be sufficient if that is preferable.

<?php
add_filter('acfcdt/filter_value_before_encode', function( $value, array $field ){
if( is_array($value) || is_object($value) ){
$value = wp_json_encode( $value, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE );
}
return $value;
}, 10, 2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment