12% off of LTD using this coupon: TWELVEPERCENTOFF. Promo ends on 2 Dec midnight UTC.
Published on Sep 16, 2019

How to get a single variable from the WordPress database for the current post

Sridhar Katakam

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

  1. use $wpdb Object’s get_var function to retrieve the value of a ListingID column in the rps_property (name without the prefix) table for the current post (a CPT entry)
  2. show how to run a shortcode using the above string as the value of listing_id parameter in Oxygen‘s Code Block
  3. 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 Code Snippets plugin

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

tagschevron-leftchevron-rightchainangle-rightangle-upangle-downfolder-omagnifiercrossmenuchevron-down