How to get a single variable from the WordPress database for the current post
In Oxygen’s Facebook group, a user wrote:
Hey guys, I am working on a real estate website with oxygen. I think I finally cracked the problem on integrating an MLS® feed into an oxygen site. I need a hand with one thing.
…
I need some code that will query the database to get the unique listing ID and insert that into a shortcode. That way I can display the data in a custom oxygen template.
This tutorial provides the steps to
- use
$wpdb
Object’sget_var
function to retrieve the value of aListingID
column in therps_property
(name without the prefix) table for the current post (a CPT entry) - show how to run a shortcode using the above string as the value of
listing_id
parameter in Oxygen‘s Code Block - define a custom shortcode that outputs the value
of ListingID
for the current post.
Code Block Component
In the Template that applies to single entries, add the following in the PHP & HTML section:
<?php
global $wpdb, $table_prefix;
$listingid = $wpdb->get_var( 'SELECT ListingID FROM ' . $table_prefix . 'rps_property WHERE PostID = ' . get_the_ID() );
echo do_shortcode( '[rps-listing-data listing_id="' . $listingid . '" key=StreetAddress]' );
?>
Sample shortcode output:
[rps-listing-data listing_id=889371854720 key=StreetAddress]
Shortcode Component
If you prefer using a shortcode instead,
a) Install and activate
b) Add a new Snippet.
Title: [Shortcode] Run [rps-listing-data] shortcode for the current listing
Code:
add_shortcode( 'my-rps-listing-data', function () {
global $wpdb, $table_prefix;
$listingid = $wpdb->get_var( 'SELECT ListingID FROM ' . $table_prefix . 'rps_property WHERE PostID = ' . get_the_ID() );
return do_shortcode( '[rps-listing-data listing_id="' . $listingid . '" key=StreetAddress]' );
} );
c) In the Template that applies to single entries, use this shortcode in a Shortcode component:
[my-rps-listing-data]
Reference
https://codex.wordpress.org/Class_Reference/wpdb#SELECT_a_Variable