I'm a developer, but inexperienced in PHP or Wordpress. Tinkering with existing WP site (using Divi theme, if that matters) and wanting to build some shortcodes that pull from the WP database. In experimenting I was able to get some custom shortcodes working (including new file into theme's functions.php). Basic ones work fine, but when I try to read from wpdb, the page throws this error:
Error: Call to undefined function get_results() in <MY_FILE>
Here's my file:
<?php
function list_users() {
global $wpdb;
$users = get_results("SELECT * FROM $wpdb->users");
$result = "<p>";
foreach ($results as $result) {
$result .= $result->display_name;
$result .= '<br>';
}
$result .= "</p>";
return $result;
}
add_shortcode( 'all_users', 'list_users' );
?>
Any advice for a PHP novice?
CodePudding user response:
You don't need to get the users from database query. WordPress provides get_users
function. So, you can try with the below code.
function list_users() {
ob_start();
$users = get_users();
foreach( $users as $user ) {
echo '<p>'. $user->data->display_name .'</p>';
}
$output = ob_get_contents();
ob_end_clean();
return $output;
}
add_shortcode( 'all_users', 'list_users' );
CodePudding user response:
Okay, the answer was obvious as I wasn't calling get_results on $wpdb.
This solved it:
<?php
function list_users() {
global $wpdb;
$users = $wpdb->get_results("SELECT * FROM $wpdb->users");
$result = "<p>";
foreach ($results as $result) {
$result .= $result->display_name;
$result .= '<br>';
}
$result .= "</p>";
return $result;
}
add_shortcode( 'all_users', 'list_users' );
?>