WordPress.org

Support

Support » How-To and Troubleshooting » How to get "key" from "value" in custom meta

How to get "key" from "value" in custom meta

  • i have a single post’s custom meta, ex:
    custom meta key = moviename
    custom meta value = HarryPotter

    i can use code:
    <?php echo get_post_meta($post->ID, ‘moviename’, true); ?>
    to get the post’s custom meta value “HarryPotter”

    but, how can i get the custom meta key “moviename”,
    with the value “HarryPotter” that i know?

    now, i use
    <?php
    $customkeys = $wpdb->get_results(“SELECT meta_key FROM $wpdb->postmeta WHERE meta_value = ‘HarryPotter'”);
    $meta_key = $customkeys[0]->meta_key;
    ?>

    just can get Key just first of one, it’s not current post Key.
    because i have more post have value”harrypotter” in different Key.

    how can i get current post that key name

Viewing 2 replies - 1 through 2 (of 2 total)
  • To get an array of all the keys and values in a specific post you could use: get_post_custom()

    <?php $my_custom = get_post_custom(); ?>

    However, since you already have to know the key to use:

    <?php echo get_post_meta($post->ID, 'moviename', true); ?>

    couldn’t you just save the key in a variable for use later?

    $my_key = 'moviename';
    <?php echo get_post_meta($post->ID, $my_key, true); ?>

    i got it,
    (“SELECT meta_key FROM $wpdb->postmeta WHERE meta_value = ‘HarryPotter'”);

    add id to

    (“SELECT meta_key FROM $wpdb->postmeta WHERE meta_value = ‘HarryPotter’ and post_id = ‘$post->ID'”);

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘How to get "key" from "value" in custom meta’ is closed to new replies.