Use a value from a database column in a shortcode to output another value in the same row
22:39 25 Feb 2026

I've searched a bunch of questions and answers here on Stack Overflow, but I can't quite find anything helpful, probably I'm not sure of the terminology to use when searching. Basically what I want to do is something like a previous question of mine Advanced Custom Fields: use a repeater subfield in a shortcode to output another subfield , but not with the Advanced Custom Fields plugin, and using a non-WordPress database table. But I want to use the WordPress database layer wpdb https://developer.wordpress.org/reference/classes/wpdb/ to make things easier and more secure.

What I want to do is use a value from a column in the database table in a shortcode to output the value in another column in the same database row when the shortcode is executed.

This is the structure of my_table:

sample database table What I need to do is loop through the "key" column and match the key that is in the shortcode, and then output the value in the same row. Like using this shortcode in WordPress content:

[product_shortcode "key1"]

should output the value 1.00

And on and on, for all the keys.

(I'm not currently using the column product_key. And using "product_shortcode" in the shortcode is simply to differentiate this set of shortcodes from others I may develop in the future.)

What's the best way to query the second column of the database for the same key that is in the shortcode? And then output the value?

I don't think I need or want to use the WordPress "if while" loop, since this is not WordPress content. And https://developer.wordpress.org/reference/functions/shortcode_atts/ appears to be strictly for WordPress shortcodes?

I do have this, which outputs all the keys:

global $wpdb;
    $table_name = "my_table";
    $the_rows = $wpdb->get_results( "SELECT `key` FROM ".$table_name);
    
    foreach ($the_rows as $data) {
        echo $data->key;
        echo ',';
}

And then I need to compare the $field from the shortcode to the $key

if ( $key === $field ) {
    return esc_html( $value );
       }

Any help is appreciated!

php mysql database wordpress shortcode