Posted By

prwhitehead on 04/17/11


Tagged

php wordpress field meta custom


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

baires


Wordpress: Return all custom fields in one session variable


 / Published in: PHP
 

Returns all of the custom fields (meta data) from a page / post and assigns them all to a single session array for compactness

  1. /**
  2. * Usage: Add all_my_customs(); to your page somewhere (header.php is best)
  3. * Usage: if you would like to get the postmeta from a specific page use, all_my_customs('7');
  4. * To access the value <?php echo $_SESSION['pc']['your_custom_name']; ?>
  5. */
  6.  
  7. function all_my_customs($id = 0){
  8.  
  9. //if a post id is not provided grab the page currently being presented
  10. if ($id == 0)
  11. {
  12. global $wp_query;
  13. $content_array = $wp_query->get_queried_object();
  14. $id = $content_array->ID;
  15. }
  16.  
  17. //grab the customs in their raw form from wp
  18. $raw = get_post_custom($id);
  19. //if the raw data is an array run a loop
  20. if (is_array($raw))
  21. {
  22. foreach($raw as $key => $value)
  23. {
  24. //if the number of items returned for the cf is greater than one (an array of items)
  25. if (count($value) > 1)
  26. {
  27. //retain all
  28. foreach($value as $v)
  29. {
  30. $return[$key][] = $v;
  31. }
  32. }
  33. //else add the first item
  34. else
  35. {
  36. $return[$key] = $value[0];
  37. }
  38. }
  39.  
  40. }
  41. //and returns the session array.
  42. $_SESSION['pc'] = $return;
  43. return $_SESSION['pc'];
  44. }

Report this snippet  

You need to login to post a comment.