functions.php
<?php
add_filter( 'get_post_metadata', 'my_custom_url_prepend_value', 99999, 4 );
/**
* Get Meta Filter
*
* Filter the get_metadata function to return specific value we
* customize.
*
* Null should be returned to allow get_metadata to proceed and
* actually get the meta. If anything other than null is returned
* that is what will be returned by get_metadata and used for output.
*
*
* @see https://developer.wordpress.org/reference/hooks/get_meta_type_metadata/
*
* @param null|array|string $null The value get_metadata() should
* return - a single metadata value,
* or an array of values.
* @param int $object_id Object ID.
* @param string $meta_key Meta key.
* @param string|array $single Meta value, or an array of values.
*
* @return mixed
*/
function my_custom_url_prepend_value( $null, $object_id, $meta_key, $single ){
/**
* You MUST prepend metakey with underscore! In example below, our meta keys
* are company_website, facebook_url, application_url
*/
$my_url_fields = array(
'_company_website',
'_facebook_url',
'_application_url'
);
// URL to prepend
$my_url_prepend = 'https://mysite.com/out.php?url=';
if( in_array( $meta_key, $my_url_fields ) ){
// We have to remove filter to prevent loop back to our function
remove_filter( 'get_post_metadata', 'my_custom_url_prepend_value', 99999 );
// Pull value from database/cache
$actual_value = get_post_meta( $object_id, $meta_key, true );
// Now we add it back for any additional fields that are called
add_filter( 'get_post_metadata', 'my_custom_url_prepend_value', 99999, 4 );
// Make sure there is a value, it's a string, and a valid URL
if( ! empty( $actual_value ) && is_string( $actual_value ) && filter_var( $actual_value, FILTER_VALIDATE_URL) ){
// Return the prepend value, plus the actual value
return $my_url_prepend . $actual_value;
}
}
// Return null to let WordPress pull value from database
return $null;
}
No comments yet.