Last active
October 8, 2024 22:20
-
-
Save bjonesy/1e95f23c38d629e95424 to your computer and use it in GitHub Desktop.
Better ways to retrieve custom fields get_post_meta()
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 | |
/** | |
* Retrieve a single value of a custom field | |
* | |
* A wrapper for get_post_meta to make it so the $post_id is not required. | |
* | |
* @param unknown $key string - the custom field key | |
* @param unknown $p_id int (optional) - the post ID for post to retrieve the value from, defaults to current post | |
*/ | |
function theme_slug_get_field( $key, $p_id=null ) { | |
// Populate $p_id if empty with the current post | |
if ( empty( $p_id ) ) { | |
$p_id = get_the_ID(); | |
} | |
return get_post_meta( $p_id, $key, true ); | |
} | |
/** | |
* Print out a single value of a custom field | |
* | |
* @param unknown $key string - the custom field key | |
* @param unknown $p_id int (optional) - the post ID for post to retrieve the value from, defaults to current post | |
*/ | |
function theme_slug_the_field( $key, $p_id=null, $esc_method='attr' ) { | |
$value = theme_slug_get_field( $key, $p_id ); | |
if ( $esc_method == 'text' ) { | |
echo esc_html( $value ); | |
} elseif ( $esc_method == 'url' ) { | |
echo esc_url( $value ); | |
} elseif ( $esc_method == 'html' ) { | |
echo wp_kses_post( $value ); | |
} else { | |
echo esc_attr( $value ); | |
} | |
} | |
/** | |
* Retrieve multiple values of a custom field | |
* | |
* @param unknown $key string - the custom field key | |
* @param unknown $p_id int (optional) - the post ID for post to retrieve the value from, defaults to current post | |
*/ | |
function theme_slug_get_multiple_field( $key, $p_id=null ) { | |
// Populate $p_id if empty with the current post | |
if ( empty( $p_id ) ) { | |
$p_id = get_the_ID(); | |
} | |
return get_post_meta( $p_id, $key, false ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment