简体   繁体   中英

How and where to get 'key' and then use it in get_post_meta()?

I am trying to use the get_post_meta($post-id, $key) method, but i run into some problem becuase I do not know the key name for the post. How can I get the key? This code is simply an example for the get_post_meta($post-id, $key) function...

<?php
$current_post_meta = get_post_meta(get_the_id(), '$the_key_i_do_not_know');
?>
<html>
<div class="container">
<?php
echo $current_post_meta[0]; //This echoes the post-id of posts with the same key as $the_key_i_do_not_know.
?>
</div>
</html>

If you have a script or some sort of way of getting a post's all keys that would be great thanks!

Best regards, Ledung.

You can use get_post_custom_keys in order to get all of the meta keys related to the post. It returns an array. Here's an example from codex:

<?php
$custom_field_keys = get_post_custom_keys();
foreach ( $custom_field_keys as $key => $value ) {
    $valuet = trim($value);
    if ( '_' == $valuet{0} )
        continue;
    echo $key . " => " . $value . "<br />";
}
?>

And here's the link to the codex: https://developer.wordpress.org/reference/functions/get_post_custom_keys/

The get_post_meta() function without a key, returns an array of all post meta for a specific post id:

$post_meta = get_post_meta(get_the_id());
print_r($post_meta); // Shows all post meta

See also: https://developer.wordpress.org/reference/functions/get_post_meta/

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