Skip to main content

Transform a stored field value before display

Free Beginner Since v1.0.0

benecaster_field_value fires on every read — including inside the episode editor UI and REST API responses. Use it to format raw stored values: convert a date string to a localized format, resolve a stored post ID to a title, or apply sanitization before display. Keep the callback fast and cache expensive lookups — it fires on every field read.

Code

<?php
add_filter( 'benecaster_field_value', function ( mixed $value, int $field_id, int $object_id, string $cpt_slug ): mixed {
    if ( null === $value ) {
        return $value;
    }

    // Example: format date fields as localized date strings.
    global $wpdb;
    static $type_cache = [];
    if ( ! isset( $type_cache[ $field_id ] ) ) {
        $type_cache[ $field_id ] = $wpdb->get_var( $wpdb->prepare(
            "SELECT field_type FROM {$wpdb->prefix}benecaster_fields WHERE id = %d LIMIT 1",
            $field_id
        ) );
    }

    if ( 'date' === $type_cache[ $field_id ] ) {
        $timestamp = strtotime( (string) $value );
        return $timestamp ? date_i18n( get_option( 'date_format' ), $timestamp ) : $value;
    }

    return $value;
}, 10, 4 );

View on GitHub →

Hooks Used