I am trying to run a "sql query" which needs a post result. I keep getting this error:

Call to a member function get_results() on a non-object in ../includes/functions.php on line 43

Here is my code:

if (isset($_GET['slug'])){
    function get_slug() {
        $slug = 'home';
        return $slug;
    }
} else {
    function get_slug() {
        $sql = "SELECT slug FROM wp_content WHERE slug='".$_GET['slug']."'";
        while ($result = $wpdb->get_results($sql)) {
            $slug = $result['slug'];
            return $slug;
        }
    }   
}

I think that the problem is in the $_GET. I've tried the "wordpress function" get_query_var('slug') instead and still the same error occurs.

有帮助吗?

解决方案

Here is the modified code. i hope it will work. if not let me know.

if (isset($_GET['slug'])){
    function get_slug() {
        $slug = 'home';
        return $slug;
    }
} else {
    function get_slug() {
        global $wpdb;
        $sql = "SELECT slug FROM wp_content WHERE slug='".$_GET['slug']."'";
        while ($result = $wpdb->get_results($sql)) {
            $slug = $result['slug'];
            return $slug;
        }
    }   
}

其他提示

Its because, $wpdb; is not accessible from inside your function.

If you add a language construct global to $wpdb, you will get this object.

PHP Global Scope

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top