简体   繁体   English

Wordpress 自定义简码:调用未定义的 function get_results()

[英]Wordpress Custom Shortcode: Call to undefined function get_results()

I'm a developer, but inexperienced in PHP or Wordpress.我是一名开发人员,但对 PHP 或 Wordpress 缺乏经验。 Tinkering with existing WP site (using Divi theme, if that matters) and wanting to build some shortcodes that pull from the WP database.修补现有的 WP 站点(使用 Divi 主题,如果重要的话)并希望构建一些从 WP 数据库中提取的短代码。 In experimenting I was able to get some custom shortcodes working (including new file into theme's functions.php).在实验中,我能够使一些自定义简码正常工作(包括将新文件放入主题的functions.php)。 Basic ones work fine, but when I try to read from wpdb, the page throws this error:基本的工作正常,但是当我尝试从 wpdb 读取时,页面会抛出此错误:

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?对 PHP 新手有什么建议吗?

You don't need to get the users from database query.您不需要从数据库查询中获取用户。 WordPress provides get_users function. WordPress 提供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' );

Okay, the answer was obvious as I wasn't calling get_results on $wpdb.好的,答案很明显,因为我没有在 $wpdb 上调用 get_results。

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

?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM