Last active
June 26, 2024 22:34
-
-
Save adeel-raza/1de811e5206401a9840d0375c6ee4a21 to your computer and use it in GitHub Desktop.
Get ACF custom field value for the current logged in WordPress user
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
/** | |
* Shortcode to get ACF field value for the current user. | |
* | |
* This shortcode retrieves the value of an Advanced Custom Fields (ACF) field | |
* for the currently logged-in user. | |
* | |
* Usage: | |
* [acf_custom_field field_name="your_acf_field_name"] | |
* | |
* The field_name attribute corresponds to the ACF field name. | |
* For more details, see the ACF documentation: | |
* https://www.advancedcustomfields.com/resources/field-settings/ | |
* | |
* @param array $atts Shortcode attributes. | |
* @return string ACF field value. | |
*/ | |
function acf_custom_field_get_shortcode( $atts ) { | |
// Extract the attributes passed to the shortcode | |
$atts = shortcode_atts( | |
array( | |
'field_name' => '', | |
), | |
$atts, | |
'acf_custom_field' | |
); | |
// Get the current user ID | |
if ( isset( $_GET['user'] ) ) { | |
$current_user_id = sanitize_text_field( $_GET['user'] ); | |
} else { | |
$current_user_id = intval( get_current_user_id() ); | |
} | |
// Ensure the field_name attribute is safe | |
$field_name = sanitize_text_field( $atts['field_name'] ); | |
if ( empty( $field_name ) || ! $current_user_id ) { | |
return ''; // Return empty string if the field name is not provided or user not logged in | |
} | |
// Return the ACF field value for the current user | |
return do_shortcode( '[acf field="' . esc_attr( $field_name ) . '" post_id="user_' . esc_attr( $current_user_id ) . '"]' ); | |
} | |
// Register the shortcode | |
add_shortcode( 'acf_custom_field', 'acf_custom_field_get_shortcode' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this code in your child theme's functions.php file and use this shortcode anywhere on your site to get the custom field value for your current logged in user as,
[acf_custom_field field_name="{your_acf_field_name}"]
The ACF field name comes from the ACF field setting for the field that you have created with ACF.
https://www.advancedcustomfields.com/resources/field-settings/