0

I am trying pass a WP function to a user function, where I can pass a new func argument $key for each post_meta type here:

functions.php

  function my_post_meta($key){
      $meta = get_post_meta($post->ID, $key, true); 
      if ($meta) {
       echo $meta . '<br />';           
     }  
   }

page-template.php

Edit: These functions will be inside a foreach() of get_posts().

my_post_meta("Author");
my_post_meta("Date") .'customise this meta key';
my_post_meta("Address") .'customise this meta key';

2 Answers 2

1

The second and third argument to get_post_meta() are optional. If not provided-- ie. get_post_meta($post->ID)-- you will get an array of all meta for the post.

If only $id is set it will return all meta values in an associative array.

http://codex.wordpress.org/Function_Reference/get_post_meta#Return_Value

For example:

$meta = get_post_meta($post->ID); 
var_dump($meta);
2
  • Thanks, you put me on the right track but I needed to take it further so not sure if I should mark as the correct answer? I do not have privileges yet anyhow :) Commented May 31, 2014 at 13:24
  • You may select answer you want, including your own, but this answers the original question better than your own answer, in my mind.
    – s_ha_dum
    Commented May 31, 2014 at 15:12
1

As I wanted to put the if() statement into a function - continuing on from s_ha_dum's help, here is my own answer. I included the second argument so as only return the keys I need.

I am passing the NULL value to two of my function arguments as way to make them optional as suggested here: ... optional parameter values in PHP.

functions.php

function jd_post_meta($strongstart = NULL, $key, $strongend = NUll){
  global $post;
  $meta = get_post_meta($post->ID, $key);
  if($meta[0]) {
    echo $boldstart.$meta[0].$boldend.'<br />';
  }
}   

page-template.php

jd_post_meta(NULL,'Author',NULL);
jd_post_meta('Translation <strong>','Translator','</strong>');
jd_post_meta(NULL,'Event-date',NULL);
jd_post_meta(NULL,'Event-address',NULL);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.