Support » Fixing WordPress » Cannot Run Query on Newly-Created Table in WordPress

  • Resolved johnwinlwin



    I can run the following query on ‘wp_links’ tables or any other built-in tables in WordPress/MySQL database.
    global $wpdb;
    $comment_count = $wpdb->get_var($wpdb->prepare(“SELECT COUNT(*) FROM $wpdb->links;”));
    echo “<p>Total comments: ” . $comment_count . “</p>”;

    PROBLEM is that after I added new table, say ‘wp_newtable’, and I tried to run the same query on ‘wp_newtable’, nothing is shown although I have put some records in wp_newtable.

    Did i miss something? Do I need to update some setting??

    Appreciate your help!

Viewing 4 replies - 1 through 4 (of 4 total)
  • If you are using $wpdb->newtable for the table name in your query, you will not get any results because $wpdb does not have a record of your new table. You must add the table to $wpdb before you use it in queries – typically in functions.php:

    <?php function my_theme_init() {
        global $wpdb;
        $wpdb->newtable = $wpdb->prefix . 'newtable';

    Hi xtxyzzy, thanks for your help.

    I found the functions.php in /wp-content/themes/ folder.

    When I open the functions.php, I found the following code:


    Can I just put your code below the above code? Thanks you again for your help. 🙂

    Hey xtxyzzy,

    I got it. Thanks again for your code. It works.

    But I’m wondering what if I create 2 new tables and those 2 tables have one-to-many relationship. Do I need to declare or specify this relationship in the WordPress?

    The relationship is expressed in the SQL of the query, so WP does not need it elsewhere.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Cannot Run Query on Newly-Created Table in WordPress’ is closed to new replies.