skip to Main Content

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?

2

Answers


  1. Chosen as BEST ANSWER

    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' );
    
    ?>
    

  2. 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' );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search