Is there a way to filter all custom fields on a post?
Lets assume for very basic simplicity I have:
standard fields of:
- title
- post body
custom fields:
- author
- ISBN
- quote
Lets assume on page load I want to append 123456 to the end of each custom fields value but that I want to do this with a filter. Which add_filter could accomplish this? A small blurb of code would be helpful.
Edit as per the current top answer:
After working the top answer I ran into an issue where it would only work on the first field. I then realized i needed to go through each element and this is what i have. What is weird is the data looks intact but the page does not display the new data. I have comments in my code below:
function my_post_meta_filters($null, $post_id, $key, $single){
if(is_admin() || (substr($key, 0, 8) != '_author_' && substr($key, 0, 7) != '_quote_')){
return $null;
}
static $filtered_values = NULL;
if(is_null($filtered_values)){
$cache = update_postmeta_cache(array($post_id));
$values = $cache[$post_id];
//must loop through all the fields or else only the first field is affected
foreach($values AS $valkey => $value){
if(substr($key, 0, 8) == '_author_' || substr($key, 0, 7) == '_quote_'){
$filtered[$valkey] = filtered($values[$valkey][0]);
$filtered[$valkey] = maybe_serialize($filtered[$valkey]); //at this point the data is correct and even reserialized where expected
$filtered_values[$valkey] = $filtered[$valkey];
}
}
return $filtered_values;
}
}
add_filter('get_post_metadata', 'my_post_meta_filters', 0, 4);
function filtered($it){
if(!is_array($it) && !is_serialized($it)){
$filtered = apply_filters('number_filter', $it); //adds numbers to the end
} else {
//otherwise we ran into a serialized array so lets unserialize and run each part through our function
$unserialized = maybe_unserialize($it);
$filtered = array_map('filtered', $unserialized);
}
return $filtered;
}