Created
October 1, 2025 22:00
-
-
Save undfine/76ceb156edb192d81c06d8297547d2e5 to your computer and use it in GitHub Desktop.
Filter calls for post_name as meta data (like a custom field)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /** | |
| * Filters get_post_metadata calls for "post_name" (post slug) which is not part of the meta data. | |
| * This can be used where dynamic codes allow using a custom-field, useful for setting the ID of an element in a loop | |
| */ | |
| function filter_get_post_name_as_meta( $value, $object_id, $meta_key, $single ) { | |
| // Only proceed if the meta key is 'post_name' and no value has been returned yet. | |
| if ( 'post_name' !== $meta_key || null !== $value ) { | |
| return $value; | |
| } | |
| $post = get_post( $object_id ); | |
| if ( $post instanceof WP_Post && property_exists( $post, 'post_name' ) ) { | |
| if ( $single ) { | |
| return $post->post_name; | |
| } | |
| return [ $post->post_name ]; | |
| } | |
| return $value; | |
| } | |
| // Hooks into the generic post metadata filter. | |
| add_filter( 'get_post_metadata', 'filter_get_post_name_as_meta', 10, 4 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment