How to display all database queries made by Wordpress?

前端 未结 4 1860
生来不讨喜
生来不讨喜 2020-12-13 05:42

Using a method similar to the one described here, I can see the total number of queries being made in Wordpress when I load a page.

Now I\'d like to display all da

相关标签:
4条回答
  • 2020-12-13 06:00

    or you can hook into posts_request. You can put the coe inside functions.php such as

    add_filter('posts_request','debug_post_request'); // debugging sql query of a post
    
    function debug_post_request($sql_text) {
    
       $GLOBALS['debugku'] = $sql_text; //intercept and store the sql<br/>
       return $sql_text; 
    
    }
    

    in your theme footer, you can use print_r like

    print_r($GLOBALS['debugku']);
    
    0 讨论(0)
  • 2020-12-13 06:05

    Use Query Monitor.

    It's a free and open-source plugin where you can filter your queries in various contexts, such as:

    • Which plugin called
    • Queries that took the most time
    • Duplicated queries
    • You can filter by Select / Update / Insert / Delete

    Among other things...

    0 讨论(0)
  • 2020-12-13 06:11

    If you add define('SAVEQUERIES', true) to your configuration file, you can then list all the queries made for the current page by adding the following to your theme.

    if (current_user_can('administrator')){
        global $wpdb;
        echo "<pre>";
        print_r($wpdb->queries);
        echo "</pre>";
    }
    

    See the documentation for more details: http://codex.wordpress.org/Editing_wp-config.php#Save_queries_for_analysis

    0 讨论(0)
  • 2020-12-13 06:17

    I like to add at the bottom of the page, queries/elapsed time, here the code:

    /**
     * show all sql at footer if it defined in wp-config.php:
     * define('SAVEQUERIES', true);
     */
    function plg_name_show_debug_queries()
    {
        if (defined('SAVEQUERIES') && SAVEQUERIES) {
            global $wpdb;
            if (is_array($wpdb->queries)) foreach ($wpdb->queries as $key => $q) {
                list($query, $elapsed, $debug) = $q;
                $time = number_format(($elapsed * 1000), 3);
                $count = $key + 1;
                $total_time += $elapsed;
                echo "
                <div style=\"position: relative; z-index: 9999    ; background: black; color: white; padding:10px\">
                    $count - Query: $query <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Time: $time ms
                </div>";
            }
            echo "
            <div style=\"position: relative; z-index: 9999    ; background: black; color: white; padding:10px\">
                Total Queries: " . count($wpdb->queries) . "<br>Total Time: " . number_format(($total_time * 1000), 3) . " ms
            </div>";
        }
    }
    add_action('admin_footer', 'plg_name_show_debug_queries', PHP_INT_MAX);
    add_action('wp_footer', 'plg_name_show_debug_queries', PHP_INT_MAX);
    
    0 讨论(0)
提交回复
热议问题