With the redesign of the Ei Site, we wanted to take advantage of certain features native to WordPress, one of which was Custom Fields.
We wanted a simple way to display our client list using Custom Fields. Using built-in WordPress functions, it is pretty simple to pull information from Custom Fields. With Custom Field structure like this:
Name: client
Value: Name|Work_Done|Description|URL
You can use the get_post_meta() function to loop through all of the ‘client’ fields and pull the value for each and display to your page.
ORIGINAL CODE:
<?php
$allOptions = get_post_meta($post->ID, 'client', false);
if($allOptions) {
foreach ($allOptions as $option) {
$fullValue = explode ("|", $option);
$name = $fullValue[0];
$work = $fullValue[1];
$text = $fullValue[2];
$url = $fullValue[3];
}
}
?>
The problem comes if you want to control the way the output is displayed. The get_post_meta() function does not provide a SORT property. So in order to control the order of display, we simply added an additional component to the VALUE field, a ‘sort order’.
Name: client
Value: Sort|Name|Work_Done|Description|URL
Rather than just display the information in the initial foreach() loop, we stored the data into a new array, based on the SORT item for use later.
NEW CODE:
<?php
$client_array = array();
$allOptions = get_post_meta($post->ID, 'client', false);
if($allOptions) {
foreach ($allOptions as $option) {
$fullValue = explode ("|", $option);
$order = $fullValue[0];
$client_array[$order] = $option;
}
}
rsort($client_array, SORT_NUMERIC);
?>
With the data now stored in an sorted array, we can now loop through the new array and display the information in any order we want.
Pingback: Sorting image from custom fields « heidzir