Support » Developing with WordPress » How to view table meta key post value?

  • How do I view post value, table meta_key? I have to retrieve a value from a post that is in a meta_key in a table. I think that in order to import the correct meta_key values, I have to import the test_id which is the id, which is in the table. how do I do that? Thanks in advance. 🙂

    <?php
        global  $wpdb;
    
        $echo_options = $wpdb->get_col("SELECT DISTINCT(meta_value) FROM $wpdb->table_test WHERE meta_key = 'test_options'" );
    
        echo "$echo_options";
        ?>

    Sorry bad english

Viewing 4 replies - 1 through 4 (of 4 total)
  • Moderator bcworkz

    (@bcworkz)

    It depends on how your table is organized. If an ID is part of the criteria, then add it to the WHERE clause. If you want a specific value from the table, use $wpdb->get_var(). get_col() will return an array of values, of which there is likely only one value you actually want. Assuming your query will include variables such as the ID, you should also use $wpdb->prepare() before hand. There is no class property for $table_test, so simply supply the actual full table name. For example:

    global  $wpdb;
    $id = get_the_ID(); // this only works with standard post loops
    $option = $wpdb->get_var( $wpdb->prepare("SELECT meta_value FROM wp_table_test WHERE meta_key = 'test_options' AND test_id = '$id'"));
    echo "Meta key value for post ID $id: $option";

    Thank you very much but unfortunately it gave fatal error

    Moderator bcworkz

    (@bcworkz)

    I got a wpdb::prepare warning when testing my code, I neglected to use proper printf() style parameters, this fixes the warning:

    global  $wpdb;
    $id = get_the_ID(); // this only works with standard post loops
    $option = $wpdb->get_var( $wpdb->prepare("SELECT meta_value FROM wp_table_test WHERE meta_key = 'test_options' AND test_id = '%d'", $id));
    echo "Meta key value for post ID $id: $option";

    As I don’t have wp_table_test in my installation, I altered the SQL to work on my site. With only the SQL altered, the above code works correctly without error. If you are getting a fatal error, there’s a context issue that’s not resolved, probably causing a syntax error. What exactly is the fatal error message?

    manoodin

    (@manoodin)

    Now he did not give the mistake. But also the value does not appear in the “echo”

    Sorry, google translate

Viewing 4 replies - 1 through 4 (of 4 total)
  • You must be logged in to reply to this topic.