简体   繁体   中英

How do I call get_post_meta properly

I'm a bit confused, but if I call get_post_meta(get_the_ID(), "event", $single = true); it returns the value for that key, but if I call it this way:

$event_page_meta = "event";


function isEvent()
{
    return get_post_meta(get_the_ID(), $event_page_meta, $single = true);
}

it returns Array of all meta. I'm rather unexperienced php-developer (mostly python), but I cannot see any difference between those two calls.

Can you explain why I cannot extract that key to a variable?

Two problems:

  1. The third argument for get_post_meta should be true or false, not a variable assignment. Just write true .

  2. $event_page_meta is not in scope within the function, you either need to pass it in as an argument or make it global.

Ether:

function isEvent($event_page_meta) {
    return get_post_meta(get_the_ID(), $event_page_meta, true);
}

//somewhere else
$something = isEvent($event_page_meta);

Or:

function isEvent() {
    global $event_page_meta;
    return get_post_meta(get_the_ID(), $event_page_meta, true);
}

...this assumes $event_page_meta contains the name of the metadata key you want to retrieve. I am not sure why it's in a variable and not just a string in your function call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM