Add Snippet To Project
Custom fields in WordPress are a powerful feature that allows you to add additional information to your posts. However, managing multiple custom field values and displaying them correctly in your site can be a bit challenging. This guide is designed to simplify the process for you. In this article, we’ll provide you step-by-step instructions on how to effectively display multiple custom field values on your WordPress website, enhancing both its functionality and appearance.
function wpturbo_display_custom_fields() {
global $post;
$custom_fields = get_post_custom($post->ID);
foreach ( $custom_fields as $field_key => $field_values ) {
if ( '_' != substr( $field_key, 0, 1 ) ) {
echo '<div class="custom-field">';
echo '<h3>' . $field_key . '</h3>';
foreach ( $field_values as $key => $value ) {
echo '<div>' . $value . '</div>';
}
echo '</div>';
}
}
}
add_action( 'the_content', 'wpturbo_display_custom_fields' );
The provided code snippet offers the functionality of displaying multiple custom fields in your WordPress post content.
First, a function called wpturbo_display_custom_fields() is defined:
function wpturbo_display_custom_fields() {
// function content
}
Within this function, the $post object is called to the global scope to apply operations on it.
global $post;
Next, the function get_post_custom($post->ID) retrieves an associative array of custom fields for the current post ID. This array is stored in the $custom_fields variable:
$custom_fields = get_post_custom($post->ID);
Now, the code iterates through each custom field using a foreach loop:
foreach ( $custom_fields as $field_key => $field_values ) {
// operations on each custom field
}
Within this loop, a conditional if statement verifies if the custom field key does not start with _. This is done because WordPress by default adds custom fields with keys starting with _ to store internal information. Thus, checking for _ at the beginning of the field key helps prevent displaying these internal fields:
if ( '_' != substr( $field_key, 0, 1 ) ) {
// operations on the custom field
}
For each individual custom field that satisfies the condition, a div element is generated with the class custom-field:
echo '<div class="custom-field">';
Next, the custom field key is displayed within h3 tags:
echo '<h3>' . $field_key . '</h3>';
Another foreach loop iterates over the values of each custom field. These values are displayed within a div:
foreach ( $field_values as $key => $value ) {
echo '<div>' . $value . '</div>';
}
To mark the end of each custom field block, a closing div tag is printed:
echo '</div>';
Finally, the function wpturbo_display_custom_fields() is hooked into the the_content action, which lets the custom fields display in the post’s content:
add_action( 'the_content', 'wpturbo_display_custom_fields' );
And that sums up how this code snippet works. It simplifies the display of multiple custom fields in your WordPress posts in a cleaner and more maintainable way.
