I am having issues returning a valid response from the below code. The intention is to return a list of cities based upon post_title().
The print_r response indicates a response is being processed (see below) however when an echo on $city is undertaken it sends an error.
add_shortcode('citylist',function(){
global $wpdb;
$country = $wpdb->prefix . 'worldcities';
$title = wp_title("",false,'right');
$args = $wpdb->get_results( "SELECT city_ascii FROM $country WHERE ranking < 2 AND country = '$title'");
foreach ($args as $city_ascii=>$city) {
print_r ($city);;
};
} );
The print _r response is as follows (note Page_Title is “Nigeria”.
StdClass Object ([city_ascii] => Ibadan) StdClass Object ([city_ascii] => Ogbomoso ...
All of the responses are expected and correct (ie. Ibadan, Ogbomoso etc).
However when this is replaced with echo, it throws an error. (see revised code below).
add_shortcode('citylist',function(){
global $wpdb;
$country = $wpdb->prefix . 'worldcities';
$title = wp_title("",false,'right');
$args = $wpdb->get_results( "SELECT city_ascii FROM $country WHERE ranking < 2 AND country = '$title'");
foreach ($args as $city_ascii=>$city) {
echo $city;;
};
} );
Any help would be appreciated.
(Note I have read the PHP manuals, reviewed previous posts here and on other boards already before anyone suggests this avenue).
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Your print_r() statement shows that your $wpdb call is returning an array of objects, and you can’t echo an object. (Unless the object has a __toString() method, but stdClass doesn’t.)
You need to get the property you seek from the object, like this: $city->city_ascii.
Also, you shouldn’t echo the content generated by a shortcode. You should instead return the string.
Code edited to use $wpdb->prepare() to protect against SQL injection (per @TomJNowell’s comment).
add_shortcode('citylist',function(){
global $wpdb;
$content = '';
$country = $wpdb->prefix . 'worldcities';
$title = wp_title("",false,'right');
$args = $wpdb->get_results(
$wpdb->prepare(
"SELECT city_ascii FROM %s WHERE ranking < 2 AND country = %s",
$country,
$title
)
);
foreach ($args as $city_ascii=>$city) {
$content .= esc_html( $city->city_ascii ) . '<br />';
};
return $content;
} );
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0